### Install placekey-py
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Install the placekey-py library using pip. Ensure you have 'geos' installed on MacOS Big Sur if 'shapely' installation fails.
```shell
pip install placekey
```
--------------------------------
### Get Prefix Distance Dictionary
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Retrieve a dictionary mapping Placekey prefix lengths to an upper bound on the maximal distance in meters. Useful for quick estimations.
```python
>>> pk.get_prefix_distance_dict()
{0: 20040000.0,
1: 20040000.0,
2: 2777000.0,
3: 1065000.0,
4: 152400.0,
5: 21770.0,
6: 8227.0,
7: 1176.0,
8: 444.3,
9: 63.47}
```
--------------------------------
### placekey.placekey.placekey_to_hex_boundary
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Gets the hexagonal boundary of a Placekey.
```APIDOC
## placekey.placekey.placekey_to_hex_boundary
### Description
Retrieves the hexagonal boundary coordinates for a given Placekey.
### Method
(Assumed to be a function call)
### Parameters
- **placekey** (string) - Required - The input Placekey.
### Request Example
(Not provided in source)
### Response
- **boundary** (list of tuples) - A list of (latitude, longitude) tuples defining the hexagonal boundary.
```
--------------------------------
### Get Placekey Prefix Distance Dictionary
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Returns a dictionary that maps the length of a shared Placekey prefix to the maximum distance in meters between two Placekeys sharing that prefix. This is useful for spatial analysis and understanding Placekey resolution.
```python
get_prefix_distance_dict()
```
--------------------------------
### Get Neighboring Placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Retrieves a set of Placekeys within a specified grid distance from a given Placekey. Useful for spatial analysis and neighborhood queries.
```python
def get_neighboring_placekeys(placekey, dist=1):
"""
Return the unordered set of Placekeys whose grid distance is `<= dist` from the given
Placekey. In this context, grid distance refers to the number of H3 cells between
two H3 cells, so that neighboring cells have distance 1, neighbors of neighbors have
distance 2, etc.
:param placekey: Placekey (string)
:param dist: size of the neighborhood around the input Placekey to return (int)
:return: Set of Placekeys (set)
"""
h3_integer = placekey_to_h3_int(placekey)
neighboring_h3 = h3_int.k_ring(h3_integer, dist)
return {h3_int_to_placekey(h) for h in neighboring_h3}
```
--------------------------------
### Build HTML Documentation
Source: https://github.com/placekey/placekey-py/blob/main/docsrc/README.md
Run this command in the ./docsrc directory to generate standard HTML documentation. The output will be in ./docsrc/build.
```shell
make clean; make html
```
--------------------------------
### Initialize PlacekeyAPI Client
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Instantiate the PlacekeyAPI client with your API key. Ensure you have a valid API key before proceeding.
```python
>>> from placekey.api import PlacekeyAPI
>>> placekey_api_key = "..."
>>> pk_api = PlacekeyAPI(placekey_api_key)
```
--------------------------------
### PlacekeyAPI Initialization
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Initialize the PlacekeyAPI client with your API key. The client automatically handles rate limiting.
```APIDOC
## PlacekeyAPI Initialization
### Description
Initialize the `PlacekeyAPI` client with your API key. The client automatically handles rate limiting.
### Method
```python
PlacekeyAPI(placekey_api_key: str)
```
### Parameters
* **placekey_api_key** (str) - Required - Your Placekey API key.
```
--------------------------------
### Build Documentation for Github Pages
Source: https://github.com/placekey/placekey-py/blob/main/docsrc/README.md
Execute this command in the ./docsrc directory to generate documentation specifically for hosting on Github Pages. The output will be moved to the ./docs directory.
```shell
make clean; make github
```
--------------------------------
### List and Access Free Placekey Datasets
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Use placekey-py to list available free datasets and retrieve their S3 locations. These locations can be used with tools like boto3 or Spark.
```python
print(pk.list_free_datasets())
print(pk.return_free_datasets_location_by_name('chipotle-locations'))
```
--------------------------------
### PlacekeyAPI Initialization
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/api.html
Initializes the PlacekeyAPI class with an API key, maximum retries, a logger, and an optional user agent comment. Sets up request headers and rate-limited functions for single and bulk requests.
```python
import hashlib
import json
import logging
import itertools
from typing import List
import requests
from ratelimit import limits, RateLimitException
from backoff import on_exception, fibo
from .__version__ import __version__
console_log = logging.StreamHandler()
console_log.setFormatter(
logging.Formatter('%(asctime)s\t%(levelname)s\t%(message)s')
)
log = logging.getLogger(__name__)
log.setLevel(logging.ERROR)
log.handlers = [console_log]
class PlacekeyAPI:
"""
PlacekeyAPI class
This class provides functionality for looking up Placekeys using the Placekey
API. Places to be looked a specified by a **place dictionary** whose keys and value types
must be a subset of
* latitude (float)
* longitude (float)
* location_name (string)
* street_address (string)
* city (string)
* region (string)
* postal_code (string)
* iso_country_code (string)
* query_id (string)
* place_metadata (dict[str,str])
See the `Placekey API documentation `_ for more
information on how to use the API.
:param api_key: Placekey API key (string)
:param max_retries: Maximum number of times to retry a failed request before
halting (int). Backoffs due to rate-limiting are included in the retry count. Defaults
to 20.
:param logger: A logging object. Logs are sent to the console by default.
:param user_agent_comment: A string to append to the client's user agent, which will be
"placekey-py/{version_number} {user_agent_comment}.
"""
URL = 'https://api.placekey.io/v1/placekey'
REQUEST_LIMIT = 1000
REQUEST_WINDOW = 60
BULK_URL = 'https://api.placekey.io/v1/placekeys'
BULK_REQUEST_LIMIT = 100
BULK_REQUEST_WINDOW = 60
MAX_BATCH_SIZE = 100
DEFAULT_USER_AGENT = 'placekey-py/{}'.format(__version__)
DEFAULT_MAX_RETRIES = 20
PLACE_METADATA_CONSTANT = 'place_metadata'
QUERY_PARAMETERS = {
'latitude',
'longitude',
'location_name',
'street_address',
'city',
'region',
'postal_code',
'iso_country_code',
'query_id',
PLACE_METADATA_CONSTANT
}
PLACE_METADATA_PARAMETERS = {
'store_id',
'phone_number',
'website',
'naics_code',
'mcc_code'
}
DEFAULT_QUERY_ID_PREFIX = "place_"
def __init__(self, api_key=None, max_retries=DEFAULT_MAX_RETRIES, logger=log,
user_agent_comment=None):
self.api_key = api_key
self.max_retries = max_retries
self.logger = logger
self.user_agent_comment = user_agent_comment
self.key_ = {
'Content-Type': 'application/json',
'User-Agent': self.DEFAULT_USER_AGENT,
'apikey': self.api_key
}
self.headers = self.key_
if isinstance(self.user_agent_comment, str):
self.headers['User-Agent'] = (
self.headers['User-Agent'] + " " + self.user_agent_comment).strip()
# Rate-limited function for a single requests
self.make_request = self._get_request_function(
url=self.URL,
calls=self.REQUEST_LIMIT,
period=self.REQUEST_WINDOW,
max_tries=self.max_retries)
self.make_bulk_request = self._get_request_function(
url=self.BULK_URL,
calls=self.BULK_REQUEST_LIMIT,
period=self.BULK_REQUEST_WINDOW,
max_tries=self.max_retries)
```
--------------------------------
### Constructing Batch Payload
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/api.html
Prepares a payload for batch Placekey requests, optionally including fields for specific data.
```python
batch_payload = {
"queries": places
}
if fields:
batch_payload['options'] = {"fields": fields}
result = self.make_bulk_request(batch_payload)
return json.loads(result.text)
```
--------------------------------
### placekey.placekey module functions
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
A collection of utility functions for Placekey manipulation and conversion.
```APIDOC
## Placekey Utility Functions
This module provides various functions for working with Placekeys, including geometric conversions and validation.
### Functions
* **`geo_to_placekey(latitude, longitude, **kwargs)`**: Converts geographic coordinates to a Placekey.
* **`geojson_to_placekeys(geojson_data)`**: Converts GeoJSON data to one or more Placekeys.
* **`get_neighboring_placekeys(placekey, distance)`**: Retrieves Placekeys in the vicinity of a given Placekey.
* **`get_prefix_distance_dict(placekey)`**: Returns a dictionary of distances to Placekey prefixes.
* **`h3_int_to_placekey(h3_int)`**: Converts an H3 integer representation to a Placekey.
* **`h3_to_placekey(h3_address)`**: Converts an H3 address string to a Placekey.
* **`placekey_distance(placekey1, placekey2)`**: Calculates the distance between two Placekeys.
* **`placekey_format_is_valid(placekey)`**: Checks if a given string is a valid Placekey format.
* **`placekey_to_geo(placekey)`**: Converts a Placekey back to its geographic coordinates.
* **`placekey_to_geojson(placekey)`**: Converts a Placekey to its GeoJSON representation.
* **`placekey_to_h3(placekey)`**: Converts a Placekey to its H3 address string.
* **`placekey_to_h3_int(placekey)`**: Converts a Placekey to its H3 integer representation.
* **`placekey_to_hex_boundary(placekey)`**: Gets the hexagonal boundary of a Placekey.
* **`placekey_to_polygon(placekey)`**: Converts a Placekey to a polygon representation.
* **`placekey_to_wkt(placekey)`**: Converts a Placekey to Well-Known Text (WKT) format.
* **`polygon_to_placekeys(polygon_data)`**: Converts polygon data to one or more Placekeys.
* **`wkt_to_placekeys(wkt_data)`**: Converts Well-Known Text (WKT) data to one or more Placekeys.
### Parameters and Responses
(Detailed parameters and response schemas for each function are not provided in the source. Refer to the library's source code or examples for specifics.)
### Example Usage (Illustrative)
```python
# Example for geo_to_placekey (parameters not specified in source)
from placekey import geo_to_placekey
placekey = geo_to_placekey(latitude=37.7749, longitude=-122.4194)
print(placekey)
# Example for placekey_format_is_valid
from placekey import placekey_format_is_valid
is_valid = placekey_format_is_valid('zzw-222@5vg-777')
print(is_valid)
```
```
--------------------------------
### placekey.placekey.placekey_to_wkt
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Converts a Placekey to its Well-Known Text (WKT) representation.
```APIDOC
## placekey.placekey.placekey_to_wkt
### Description
Converts a Placekey into its Well-Known Text (WKT) string representation, typically for geometric data.
### Method
(Assumed to be a function call)
### Parameters
- **placekey** (string) - Required - The input Placekey.
### Request Example
(Not provided in source)
### Response
- **wkt_string** (string) - The WKT representation of the Placekey's geometry.
```
--------------------------------
### placekey_to_hex_boundary()
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
Converts a Placekey into its hexagonal boundary representation.
```APIDOC
## placekey_to_hex_boundary()
### Description
Converts a Placekey into its hexagonal boundary representation.
### Method
(Not specified in source, likely a Python function call)
### Endpoint
(Not applicable for SDK function)
### Parameters
(Parameters not detailed in the provided source, but would typically include a Placekey string)
### Request Example
(Not specified in source)
### Response
#### Success Response
(Response details not specified in source, but would typically be a representation of the hexagonal boundary, e.g., a list of coordinates)
#### Response Example
(Not specified in source)
```
--------------------------------
### Lookup Multiple Placekeys in Batch
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Efficiently look up Placekeys for a list of places using the `lookup_placekeys` method. Supports mixed input types (address and coordinates) and custom query IDs.
```python
>>> places = [
>>> {
>>> "street_address": "1543 Mission Street, Floor 3",
>>> "city": "San Francisco",
>>> "region": "CA",
>>> "postal_code": "94105",
>>> "iso_country_code": "US"
>>> },
>>> {
>>> "query_id": "thisqueryidaloneiscustom",
>>> "location_name": "Twin Peaks Petroleum",
>>> "street_address": "598 Portola Dr",
>>> "city": "San Francisco",
>>> "region": "CA",
>>> "postal_code": "94131",
>>> "iso_country_code": "US"
>>> },
>>> {
>>> "latitude": 37.7371,
>>> "longitude": -122.44283
>>> }
>>> ]
>>> pk_api.lookup_placekeys(places, fields=["building_placekey","address_placekey","confidence_score","gers"])
[{'query_id': 'place_0',
'placekey': '0rsdbudq45@5vg-7gq-5mk',
'address_placekey': '0rsdbudq45@5vg-7gq-5mk',
'building_placekey': '22g@5vg-7gq-5mk',
'confidence_score': 'HIGH',
'gers': None},
{'query_id': 'thisqueryidaloneiscustom',
'placekey': '227-223@5vg-82n-pgk',
'address_placekey': '227@5vg-82n-pgk',
'building_placekey': '227@5vg-82n-pgk',
'confidence_score': 'HIGH',
'gers': None},
{'query_id': 'place_2',
'placekey': '@5vg-82n-kzz',
'confidence_score': 'HIGH',
'gers': None}]
```
--------------------------------
### placekey.placekey.wkt_to_placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Generates Placekeys from a Well-Known Text (WKT) string.
```APIDOC
## placekey.placekey.wkt_to_placekeys
### Description
Processes a Well-Known Text (WKT) string and returns a list of Placekeys that intersect with the geometry defined by the WKT.
### Method
(Assumed to be a function call)
### Parameters
- **wkt_string** (string) - Required - The WKT string defining the geometry.
### Request Example
(Not provided in source)
### Response
- **placekeys** (list of strings) - A list of generated Placekeys.
```
--------------------------------
### Convert Latitude/Longitude to Placekey
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Convert a given latitude and longitude to a Placekey. This is a basic conversion function.
```python
>>> import placekey as pk
>>> lat, long = 0.0, 0.0
>>> pk.geo_to_placekey(lat, long)
'@dvt-smp-tvz'
```
--------------------------------
### polygon_to_placekeys()
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
Converts polygon data into a list of Placekeys.
```APIDOC
## polygon_to_placekeys()
### Description
Converts polygon data into a list of Placekeys.
### Method
(Not specified in source, likely a Python function call)
### Endpoint
(Not applicable for SDK function)
### Parameters
(Parameters not detailed in the provided source, but would typically include polygon data)
### Request Example
(Not specified in source)
### Response
#### Success Response
(Response details not specified in source, but would typically be a list of Placekeys)
#### Response Example
(Not specified in source)
```
--------------------------------
### Lookup Single Placekey by Address Details
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Retrieve a Placekey using detailed address information. Specify desired fields for the returned data.
```python
>>> place = {
>>> "location_name": "Twin Peaks Petroleum",
>>> "street_address": "598 Portola Dr",
>>> "city": "San Francisco",
>>> "region": "CA",
>>> "postal_code": "94131",
>>> "iso_country_code": "US"
>>> }
>>> pk_api.lookup_placekey(**place, fields="building_placekey","address_placekey","confidence_score","gers", "address_confidence_score"])
{
'query_id': '0',
'placekey': '227-223@5vg-82n-pgk',
'address_placekey': '227@5vg-82n-pgk',
'building_placekey': '227@5vg-82n-pgk',
'confidence_score': 'HIGH',
'address_confidence_score': 'HIGH',
'gers': None
}
```
--------------------------------
### PlacekeyAPI
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/api.html
The PlacekeyAPI class provides functionality for looking up Placekeys using the Placekey API. It supports looking up single places and multiple places in bulk.
```APIDOC
## Class: PlacekeyAPI
### Description
This class provides functionality for looking up Placekeys using the Placekey API. Places to be looked up are specified by a **place dictionary** whose keys and value types must be a subset of:
* latitude (float)
* longitude (float)
* location_name (string)
* street_address (string)
* city (string)
* region (string)
* postal_code (string)
* iso_country_code (string)
* query_id (string)
* place_metadata (dict[str,str])
See the `Placekey API documentation `_ for more information on how to use the API.
### Parameters
* **api_key** (string) - Placekey API key.
* **max_retries** (int) - Maximum number of times to retry a failed request before halting. Backoffs due to rate-limiting are included in the retry count. Defaults to 20.
* **logger** - A logging object. Logs are sent to the console by default.
* **user_agent_comment** (string) - A string to append to the client's user agent, which will be "placekey-py/{version_number} {user_agent_comment}".
```
--------------------------------
### placekey_to_wkt
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Placekey into its Well-Known Text (WKT) string representation for the corresponding hexagon.
```APIDOC
## placekey_to_wkt
### Description
Convert a Placekey into the WKT (Well-Known Text) string for the corresponding hexagon. Coordinates are (longitude, latitude).
### Parameters
* **placekey** (string) - Required - The input Placekey.
* **geo_json** (bool) - Optional - If True, return coordinates in GeoJSON format ((long, lat)-tuples, first and last identical, counter-clockwise). If False (default), tuples will be (lat, long), the last tuple will not equal the first, and the orientation will be clockwise.
### Returns
* WKT (Well-Known Text) polygon (string)
```
--------------------------------
### Parse Placekey into What and Where
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Internal helper function to split a Placekey string into its 'what' (optional) and 'where' components. Handles cases with and without the '@' separator.
```python
def _parse_placekey(placekey):
"""
Split a Placekey in to what and where parts.
:param placekey: Placekey (string)
:return: what (string), where (string)
"""
if '@' in placekey:
what, where = placekey.split('@')
else:
what, where = None, placekey
return what, where
```
--------------------------------
### Lookup Placekeys for a Single Batch
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/api.html
Use this method to look up Placekeys for a single batch of places. The batch size is limited to 100 places and respects API rate limits.
```python
def _lookup_batch(self, places,
fields=None):
"""
Lookup Placekeys for a single batch of places specified by place dictionaries.
The batch size can be at most 100 places. This method respects the rate limits
of the Placekey API.
:param places: An iterable of of place dictionaries.
:param fields: A list of requested parameters other than placekey. For example: address_placekey, building_placekey
Defaults to None
:return: A list of Placekey API responses for each place (list(dict))
"""
if len(places) > self.MAX_BATCH_SIZE:
raise ValueError(
'{} places submitted. The number of places in a batch can be at most {}'
```
--------------------------------
### Clean Placekey String with Replacements
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Applies a series of string replacements to clean or normalize a string according to a predefined replacement map. Replacements are applied in a specific order.
```python
def _clean_string(s):
# Replacement should be in order
for k, v in REPLACEMENT_MAP:
if k in s:
s = s.replace(k, v)
return s
```
--------------------------------
### placekey.placekey.h3_int_to_placekey
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Converts an H3 integer representation to a Placekey.
```APIDOC
## placekey.placekey.h3_int_to_placekey
### Description
Converts a numerical H3 index into its corresponding Placekey string.
### Method
(Assumed to be a function call)
### Parameters
- **h3_int** (int) - Required - The H3 index as an integer.
### Request Example
(Not provided in source)
### Response
- **placekey** (string) - The generated Placekey.
```
--------------------------------
### placekey.placekey.polygon_to_placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Generates Placekeys for a given polygon.
```APIDOC
## placekey.placekey.polygon_to_placekeys
### Description
Generates a list of Placekeys that fall within the boundaries of a provided polygon.
### Method
(Assumed to be a function call)
### Parameters
- **polygon** (object) - Required - A polygon object.
### Request Example
(Not provided in source)
### Response
- **placekeys** (list of strings) - A list of generated Placekeys.
```
--------------------------------
### h3_to_placekey()
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
Converts an H3 string representation to a Placekey.
```APIDOC
## h3_to_placekey()
### Description
Converts an H3 string representation to a Placekey.
### Method
(Not specified in source, likely a Python function call)
### Endpoint
(Not applicable for SDK function)
### Parameters
(Parameters not detailed in the provided source, but would typically include an H3 string)
### Request Example
(Not specified in source)
### Response
#### Success Response
(Response details not specified in source, but would typically be a Placekey string)
#### Response Example
(Not specified in source)
```
--------------------------------
### Calculate Placekey Distance
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Calculates the distance in meters between the centers of two Placekeys. Requires valid Placekey strings as input.
```python
def placekey_distance(placekey_1, placekey_2):
"""
Return the distance in meters between the centers of two Placekeys.
:param placekey_1: Placekey (string)
:param placekey_2: Placekey (string)
:return: distance in meters (float)
"""
geo_1 = h3_int.h3_to_geo(placekey_to_h3_int(placekey_1))
geo_2 = h3_int.h3_to_geo(placekey_to_h3_int(placekey_2))
return _geo_distance(geo_1, geo_2)
```
--------------------------------
### Validate Placekey Format
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Check if a given string conforms to the standard Placekey format. Returns True for valid formats and False otherwise.
```python
>>> pk.placekey_format_is_valid('222-227@dvt-smp-tvz')
True
```
```python
>>> pk.placekey_format_is_valid('@123-456-789')
False
```
--------------------------------
### wkt_to_placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Well-Known Text (WKT) polygon string into a list of Placekeys that are contained within or intersect the polygon's boundary.
```APIDOC
## wkt_to_placekeys
### Description
Converts a Well-Known Text (WKT) polygon string into a list of Placekeys that are contained within or intersect the polygon's boundary.
### Parameters
* **wkt** (string) - Required - The Well-Known Text representation of the polygon.
* **include_touching** (boolean) - Optional - If True, includes Placekeys whose hexagon boundary only touches the input polygon's boundary. Defaults to False.
* **geo_json** (boolean) - Optional - If True, assumes coordinates are in GeoJSON format (longitude, latitude). Defaults to False (latitude, longitude).
### Return
List of Placekeys.
```
--------------------------------
### Lookup Single Placekey by Coordinates
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Use the `lookup_placekey` method to find the Placekey for a specific location using latitude and longitude.
```python
>>> pk_api.lookup_placekey(latitude=37.7371, longitude=-122.44283)
{'query_id': '0', 'placekey': '@5vg-82n-kzz'}
```
--------------------------------
### Convert Placekey to Well-Known Text (WKT)
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Placekey to its Well-Known Text (WKT) string representation. The output coordinates are in (longitude, latitude) format.
```python
def placekey_to_wkt(placekey, geo_json=False):
"""
Convert a Placekey into the WKT (Well-Known Text) string for the
corresponding hexagon. Coordinates are (longitude, latitude).
:param placekey: Placekey (string)
:param geo_json: If True return the coordinates in GeoJSON format:
(long, lat)-tuples and with the first and last tuples identical, and in
counter-clockwise orientation. If False (default) tuples will be
(lat, long), the last tuple will not equal the first, and the orientation
will be clockwise.
:return: WKT (Well-Known Text) polygon (string)
"""
return placekey_to_polygon(placekey, geo_json=geo_json).wkt
```
--------------------------------
### placekey.placekey.placekey_to_h3
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Converts a Placekey to its H3 string representation.
```APIDOC
## placekey.placekey.placekey_to_h3
### Description
Converts a Placekey into its corresponding H3 index, returned as a string.
### Method
(Assumed to be a function call)
### Parameters
- **placekey** (string) - Required - The input Placekey.
### Request Example
(Not provided in source)
### Response
- **h3_string** (string) - The H3 index as a string.
```
--------------------------------
### Convert Placekey to Latitude/Longitude
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Convert a given Placekey back to its approximate latitude and longitude coordinates. Note the slight precision difference.
```python
>>> pk.placekey_to_geo('@dvt-smp-tvz')
(0.00018033323813810344, -0.00018985758738881587)
```
--------------------------------
### h3_to_placekey
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts an H3 hexadecimal string into a Placekey string.
```APIDOC
## h3_to_placekey
### Description
Convert an H3 hexadecimal string into a Placekey string.
### Parameters
* **h3_string** (string) - The H3 string to convert.
### Returns
* **Placekey** (string) - The generated Placekey string.
```
--------------------------------
### Validating Placekey Query Parameters
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/api.html
Ensures that a query dictionary adheres to the expected top-level and Place metadata parameters.
```python
def _validate_query(self, query_dict):
query_dict_keys = query_dict.keys()
top_level_check = set(query_dict_keys).issubset(self.QUERY_PARAMETERS)
place_metadata_check = set(query_dict.get(self.PLACE_METADATA_CONSTANT).keys()).issubset(self.PLACE_METADATA_PARAMETERS) if(self.PLACE_METADATA_CONSTANT in query_dict_keys) else True
return top_level_check and place_metadata_check
```
--------------------------------
### Calculate Distance Between Two Placekeys
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Calculate the distance in meters between two Placekeys. This function provides a precise distance calculation.
```python
>>> pk.placekey_distance('@dvt-smp-tvz', '@5vg-7gq-tjv')
12795124.895573696
```
--------------------------------
### h3_int_to_placekey
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts an H3 integer index into a Placekey string.
```APIDOC
## h3_int_to_placekey
### Description
Convert an H3 integer into a Placekey.
### Parameters
* **h3_integer** (int) - The H3 index.
### Returns
* **Placekey** (string) - The generated Placekey string.
```
--------------------------------
### Convert Placekey to H3 Index
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Convert a Placekey to its corresponding H3 index. This leverages the H3-py library.
```python
>>> pk.placekey_to_h3('@dvt-smp-tvz')
'8a754e64992ffff'
```
--------------------------------
### PlacekeyAPI Class
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
The PlacekeyAPI class provides methods to look up Placekeys using the Placekey API. It accepts a place dictionary with various location details.
```APIDOC
## Class: PlacekeyAPI
### Description
This class provides functionality for looking up Placekeys using the Placekey API. Places to be looked up are specified by a **place dictionary** whose keys and value types must be a subset of:
* latitude (float)
* longitude (float)
* location_name (string)
* street_address (string)
* city (string)
* region (string)
* postal_code (string)
* iso_country_code (string)
* query_id (string)
* place_metadata (dict[str,str])
See the [Placekey API documentation](https://docs.placekey.io/) for more information on how to use the API.
### Parameters
* **api_key** (string) – Placekey API key
* **max_retries** (int) – Maximum number of times to retry a failed request before halting. Defaults to 20.
* **logger** – A logging object. Logs are sent to the console by default.
* **user_agent_comment** (string) – A string to append to the client’s user agent.
```
--------------------------------
### placekey.placekey.h3_to_placekey
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Converts an H3 string representation to a Placekey.
```APIDOC
## placekey.placekey.h3_to_placekey
### Description
Converts an H3 index, provided as a string, into its corresponding Placekey string.
### Method
(Assumed to be a function call)
### Parameters
- **h3_string** (string) - Required - The H3 index as a string.
### Request Example
(Not provided in source)
### Response
- **placekey** (string) - The generated Placekey.
```
--------------------------------
### placekey_to_wkt
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
Converts a Placekey into its Well-Known Text (WKT) string representation. Supports GeoJSON coordinate format.
```APIDOC
## placekey_to_wkt
### Description
Convert a Placekey into the WKT (Well-Known Text) string for the corresponding hexagon. Coordinates are (longitude, latitude).
### Parameters
* **placekey** (string) - Required - Placekey identifier.
* **geo_json** (boolean) - Optional - If True, return coordinates in GeoJSON format (long, lat)-tuples, with the first and last tuples identical, and in counter-clockwise orientation. If False (default), tuples will be (lat, long), the last tuple will not equal the first, and the orientation will be clockwise.
### Returns
WKT (Well-Known Text) polygon (string).
```
--------------------------------
### Convert WKT to Placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Well-Known Text (WKT) polygon into a list of Placekeys. Supports including touching Placekeys and specifying coordinate format (GeoJSON or lat/long).
```python
def wkt_to_placekeys(wkt, include_touching=False, geo_json=False):
"""
Given a WKT description of a polygon, return Placekeys contained in
or intersecting the boundary of the polygon.
:param wkt: Well-Known Text object (string)
:param include_touching: If True Placekeys whose hexagon boundary only touches
that of the input polygon are included in the set of boundary Placekeys.
Default is False.
:param geo_json: If True assume coordinates in `poly` are in GeoJSON format:
(long, lat)-tuples and with the first and last tuples identical, and in
counter-clockwise orientation. If False (default) assumes tuples will be
(lat, long).
:return: List of Placekeys
"""
return polygon_to_placekeys(
wkt_loads(wkt), include_touching=include_touching, geo_json=geo_json)
```
--------------------------------
### placekey_to_hex_boundary
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Placekey into the coordinates of its hexagonal boundary.
```APIDOC
## placekey_to_hex_boundary
### Description
Given a Placekey, return the coordinates of the boundary of the hexagon.
### Parameters
* **placekey** (string) - Required - The input Placekey.
* **geo_json** (bool) - Optional - If True, return coordinates in GeoJSON format ((long, lat)-tuples, first and last identical, counter-clockwise). If False (default), tuples will be (lat, long), the last tuple will not equal the first, and the orientation will be clockwise.
### Returns
* Tuple of tuples ((float, float),...)
```
--------------------------------
### lookup_placekeys
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Lookup Placekeys for multiple places provided as a list of dictionaries. You can specify which fields to return for each place.
```APIDOC
## lookup_placekeys
### Description
Lookup Placekeys for multiple places provided as a list of dictionaries. You can specify which fields to return for each place.
### Method
```python
lookup_placekeys(places: list, fields: list = None)
```
### Parameters
#### Path Parameters
None
#### Query Parameters
* **places** (list) - Required - A list of dictionaries, where each dictionary represents a place and can contain coordinates or address details.
* **fields** (list) - Optional - A list of fields to include in the response for each place.
### Response
#### Success Response (200)
* A list of dictionaries, where each dictionary contains the Placekey information for a corresponding input place.
### Request Example
```python
places = [
{
"street_address": "1543 Mission Street, Floor 3",
"city": "San Francisco",
"region": "CA",
"postal_code": "94105",
"iso_country_code": "US"
},
{
"query_id": "thisqueryidaloneiscustom",
"location_name": "Twin Peaks Petroleum",
"street_address": "598 Portola Dr",
"city": "San Francisco",
"region": "CA",
"postal_code": "94131",
"iso_country_code": "US"
},
{
"latitude": 37.7371,
"longitude": -122.44283
}
]
placekey_api.lookup_placekeys(places, fields=["building_placekey","address_placekey","confidence_score","gers"])
```
### Response Example
```json
[
{
"query_id": "place_0",
"placekey": "0rsdbudq45@5vg-7gq-5mk",
"address_placekey": "0rsdbudq45@5vg-7gq-5mk",
"building_placekey": "22g@5vg-7gq-5mk",
"confidence_score": "HIGH",
"gers": null
},
{
"query_id": "thisqueryidaloneiscustom",
"placekey": "227-223@5vg-82n-pgk",
"address_placekey": "227@5vg-82n-pgk",
"building_placekey": "227@5vg-82n-pgk",
"confidence_score": "HIGH",
"gers": null
},
{
"query_id": "place_2",
"placekey": "@5vg-82n-kzz",
"confidence_score": "HIGH",
"gers": null
}
]
```
```
--------------------------------
### PlacekeyAPI.lookup_placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Looks up multiple Placekeys in a batch request.
```APIDOC
## PlacekeyAPI.lookup_placekeys
### Description
Performs a batch lookup for multiple Placekeys, allowing for efficient processing of several location inputs.
### Method
(Assumed to be a method call within the PlacekeyAPI class)
### Parameters
(Specific parameters are not detailed in the source, but would typically include a list of location data.)
### Request Example
(Not provided in source)
### Response
(Specific response structure not detailed in source, but would typically be a list of Placekeys or related data.)
```
--------------------------------
### placekey_to_h3
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Placekey string into its corresponding H3 string representation.
```APIDOC
## placekey_to_h3
### Description
Convert a Placekey string into an H3 string.
### Parameters
* **placekey** (string) - The Placekey string to convert.
### Returns
* **H3** (string) - The H3 string representation.
```
--------------------------------
### Encode Short H3 Integer to Placekey String
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Encodes a short H3 integer into a Placekey string. It cleans the encoded string, pads it to a fixed length, and formats it into tuples separated by hyphens, prefixed with '@'.
```python
encoded_short_h3 = _encode_short_int(short_h3_integer)
clean_encoded_short_h3 = _clean_string(encoded_short_h3)
if len(clean_encoded_short_h3) <= CODE_LENGTH:
clean_encoded_short_h3 = str.rjust(clean_encoded_short_h3, CODE_LENGTH, PADDING_CHAR)
return '@' + '-'.join(clean_encoded_short_h3[i:i + TUPLE_LENGTH]
for i in range(0, len(clean_encoded_short_h3), TUPLE_LENGTH))
```
--------------------------------
### Creating a Rate-Limited Request Function
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/api.html
Constructs a function to make POST requests with rate limiting and exception handling for rate limit exceedances.
```python
def _get_request_function(self, url, calls, period, max_tries):
"""
Construct a rate limited function for making requests.
:param url: request URL
:param calls: number of calls that can be made in time period
:param period: length of rate limiting time period in seconds
:param max_tries: the maximum number of retries before giving up
"""
@on_exception(fibo, RateLimitException, max_tries=max_tries)
@limits(calls=calls, period=period)
def make_request(data):
response = requests.post(
url, headers=self.headers,
data=json.dumps(data).encode('utf-8')
)
if response.status_code == 429:
raise RateLimitException("Rate limit exceeded", 0)
# Assumption: A code other than 429 is handled by calling function
return response
return make_request
```
--------------------------------
### Reverse Placekey String Replacements
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Reverses the cleaning process by applying replacements in the reverse order of the predefined replacement map. This is used to 'dirty' a cleaned string.
```python
def _dirty_string(s):
# Replacement should be in (reversed) order
for k, v in REPLACEMENT_MAP[::-1]:
if v in s:
s = s.replace(v, k)
return s
```
--------------------------------
### placekey_distance
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Calculates the distance in meters between the centers of two Placekeys.
```APIDOC
## placekey_distance
### Description
Calculates the distance in meters between the centers of two Placekeys.
### Parameters
* **placekey_1** (string) - Required - The first Placekey.
* **placekey_2** (string) - Required - The second Placekey.
### Return
The distance in meters between the two Placekeys (float).
```
--------------------------------
### placekey.placekey.placekey_format_is_valid
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Checks if a given string is a valid Placekey format.
```APIDOC
## placekey.placekey.placekey_format_is_valid
### Description
Validates whether a provided string adheres to the standard Placekey format.
### Method
(Assumed to be a function call)
### Parameters
- **placekey_string** (string) - Required - The string to validate.
### Request Example
(Not provided in source)
### Response
- **is_valid** (boolean) - True if the format is valid, False otherwise.
```
--------------------------------
### _placekey_pandas_df
Source: https://github.com/placekey/placekey-py/blob/main/README.md
Process a Pandas DataFrame to add Placekeys. This method requires column mappings to align DataFrame columns with expected Placekey API fields.
```APIDOC
## _placekey_pandas_df
### Description
Process a Pandas DataFrame to add Placekeys. This method requires column mappings to align DataFrame columns with expected Placekey API fields.
### Method
```python
_placekey_pandas_df(df: pd.DataFrame, column_mappings: dict, fields: list = None)
```
### Parameters
#### Path Parameters
None
#### Query Parameters
* **df** (pd.DataFrame) - Required - The input Pandas DataFrame.
* **column_mappings** (dict) - Required - A dictionary mapping DataFrame column names to Placekey API field names.
* **fields** (list) - Optional - A list of fields to include in the output DataFrame.
### Response
#### Success Response (200)
* A Pandas DataFrame with added Placekey columns.
### Request Example
```python
import pandas as pd
df = pd.DataFrame({
"address": ["1543 Mission Street, Floor 3", "598 Portola Dr", None],
"city": ["San Francisco", "San Francisco", None],
"region": ["CA", "CA", None],
"postal": ["94105", "94131", None],
"country": ["US", "US", None],
"latitude": [None, None, 37.7371],
"longitude": [None, None, -122.44283]
})
column_mappings = {
"street_address": "address",
"city": "city",
"region": "region",
"postal_code": "postal",
"iso_country_code": "country",
"latitude": "latitude",
"longitude": "longitude"
}
df_with_placekeys = pk_api._placekey_pandas_df(df, column_mappings, fields=['address_placekey', 'address_confidence_score'])
print(df_with_placekeys)
```
### Response Example
```
address city region postal country latitude longitude placekey address_placekey
0 1543 Mission Street, Floor 3 San Francisco CA 94105 US NaN NaN 22g@5vg-7gq-5mk 22g@5vg-7gq-5mk
1 598 Portola Dr San Francisco CA 94131 US NaN NaN 227@5vg-82n-pgk 227@5vg-82n-pgk
2 None None None None None 37.7371 -122.44283 @5vg-82n-kzz NaN
```
```
--------------------------------
### placekey_to_polygon()
Source: https://github.com/placekey/placekey-py/blob/main/docs/placekey.html
Converts a Placekey into a polygon representation.
```APIDOC
## placekey_to_polygon()
### Description
Converts a Placekey into a polygon representation.
### Method
(Not specified in source, likely a Python function call)
### Endpoint
(Not applicable for SDK function)
### Parameters
(Parameters not detailed in the provided source, but would typically include a Placekey string)
### Request Example
(Not specified in source)
### Response
#### Success Response
(Response details not specified in source, but would typically be a polygon object)
#### Response Example
(Not specified in source)
```
--------------------------------
### Convert Polygon to Placekeys
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Given a shapely Polygon, returns Placekeys that are contained within or intersect its boundary. Optionally includes Placekeys that only touch the boundary.
```python
def polygon_to_placekeys(poly, include_touching=False, geo_json=False):
"""
Given a shapely Polygon, return Placekeys contained in
or intersecting the boundary of the polygon.
:param poly: shapely Polygon object
:param include_touching: If True Placekeys whose hexagon boundary only touches
that of the input polygon are included in the set of boundary Placekeys.
Default is False.
:param geo_json: If True assume coordinates in `poly` are in GeoJSON format:
(long, lat)-tuples and with the first and last tuples identical, and in
counter-clockwise orientation. If False (default) assumes tuples will be
(lat, long).
:return: A dictionary with keys 'interior' and 'boundary' whose values are
tuples of Placekeys that are contained in poly or which intersect the
boundary of poly respectively.
"""
if geo_json:
poly = transform(lambda x, y: (y, x), poly)
buffer_size = 2e-3
buffered_poly = poly.buffer(buffer_size)
candidate_hexes = h3_int.polyfill(mapping(buffered_poly), 10)
tree = STRtree([poly])
interior_hexes = []
boundary_hexes = []
for h in list(candidate_hexes):
hex_poly = Polygon(h3_int.h3_to_geo_boundary(h))
if len(tree.query(hex_poly)) > 0:
```
--------------------------------
### placekey.placekey.placekey_to_h3_int
Source: https://github.com/placekey/placekey-py/blob/main/docs/modules.html
Converts a Placekey to its H3 integer representation.
```APIDOC
## placekey.placekey.placekey_to_h3_int
### Description
Converts a Placekey into its corresponding H3 index, returned as an integer.
### Method
(Assumed to be a function call)
### Parameters
- **placekey** (string) - Required - The input Placekey.
### Request Example
(Not provided in source)
### Response
- **h3_int** (int) - The H3 index as an integer.
```
--------------------------------
### Convert Placekey to H3 String
Source: https://github.com/placekey/placekey-py/blob/main/docs/_modules/placekey/placekey.html
Converts a Placekey string into its corresponding H3 hexadecimal string representation. This is useful for interoperability with H3-based systems.
```python
placekey_to_h3(placekey)
```