Google's Encoded Polyline Algorithm (Python)
The `polyline` library is a Python implementation of Google's Encoded Polyline Algorithm Format. It provides functionality to encode a list of latitude/longitude coordinates into a compact polyline string and to decode such a string back into coordinates. The library is actively maintained, with the current stable version being 2.0.4, and is released on an as-needed basis for bug fixes and feature enhancements.
Warnings
- breaking Version 2.0.0 and above of `polyline` only supports Python 3.7+. For applications requiring Python 2 support, you must install version 1.4.0.
- gotcha The `polyline` library uses `(latitude, longitude)` order by default for `encode` input and `decode` output, which is common in GIS but differs from the `(longitude, latitude)` order used in GeoJSON standards.
- gotcha The `precision` parameter (defaulting to 5) must be consistent between encoding and decoding operations to ensure accurate round-tripping of coordinates.
- gotcha When loading polyline strings from external sources like CSV files, be mindful of backslash escaping. Python's CSV reader or other parsing mechanisms might interpret `\` differently, leading to corrupted polyline strings.
Install
-
pip install polyline
Imports
- encode
import polyline polyline.encode(...)
- decode
import polyline polyline.decode(...)
Quickstart
import polyline
# Example coordinates: (latitude, longitude)
coords = [
(38.5, -120.2),
(40.7, -120.9),
(43.2, -126.4)
]
# Encode coordinates into a polyline string with default precision (5)
encoded_polyline = polyline.encode(coords)
print(f"Encoded Polyline: {encoded_polyline}")
# Decode the polyline string back to coordinates
decoded_coords = polyline.decode(encoded_polyline)
print(f"Decoded Coordinates: {decoded_coords}")
# Example with GeoJSON style (lon, lat) and custom precision
geojson_coords = [
(-120.2, 38.5),
(-120.9, 40.7),
(-126.4, 43.2)
]
encoded_geojson = polyline.encode(geojson_coords, precision=6, geojson=True)
print(f"Encoded GeoJSON Polyline (precision 6): {encoded_geojson}")
decoded_geojson = polyline.decode(encoded_geojson, precision=6, geojson=True)
print(f"Decoded GeoJSON Coordinates (precision 6): {decoded_geojson}")