Google's Encoded Polyline Algorithm (Python)

2.0.4 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates encoding a list of `(latitude, longitude)` tuples into a polyline string and then decoding it back. It also shows how to handle GeoJSON-style `(longitude, latitude)` order using the `geojson=True` parameter and how to specify a custom precision.

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}")

view raw JSON →