Skip to content

Polyline

Encode and decode Google's Encoded Polyline Algorithm Format — lists of coordinates as compact ASCII strings.

Implements Encoded Polyline Algorithm Format. Spec v0.1.1; every port passes the same 44 conformance cases.

Nim v0.1.0Zig v0.1.0Julia registration pending

Install

Terminal window
nimble install polyline

Examples

The same three examples exist in every port, runnable as-is from each repository's examples/ folder.

Encode a three-point route

examples/encode_route.nim
## Canonical example `encode_route`: encode a three-point route and print the string.
import polyline
let route = [
LonLat(lon: -120.2, lat: 38.5),
LonLat(lon: -120.95, lat: 40.7),
LonLat(lon: -126.453, lat: 43.252),
]
echo encode(route)

Decode Google's documented example

examples/decode_route.nim
## Canonical example `decode_route`: decode Google's example and print each point.
import polyline
try:
for p in decode("_p~iF~ps|U_ulLnnqC_mqNvxq`@"):
echo "lon ", p.lon, ", lat ", p.lat
except PolylineError as e:
stderr.writeLine e.kind, ": ", e.code, " at byte ",
(if e.offset.isSome: $e.offset.get else: "?")
quit 1

Round-trip a route at precision 6

examples/precision_6.nim
## Canonical example `precision_6`: round-trip a route at precision 6 (OSRM, Valhalla).
import polyline
let route = [
LonLat(lon: -73.985713, lat: 40.748441),
LonLat(lon: -73.978569, lat: 40.751657),
LonLat(lon: -73.968285, lat: 40.785091),
]
let text = encode(route, precision = 6)
let back = decode(text, precision = 6)
echo text
for i, a in route:
let b = back[i]
echo "(", a.lon, ", ", a.lat, ") -> (", b.lon, ", ", b.lat, ")"
if abs(a.lon - b.lon) > 1e-6 or abs(a.lat - b.lat) > 1e-6:
quit "round trip mismatch", 1
echo "round trip matches"

Ports

LanguagePackageReleaseSpecConformance
Nimpolylinev0.1.0v0.1.1core ✓ full ✓ (44/44)
Zigpolylinev0.1.0v0.1.1core ✓ full ✓ (44/44)
JuliaEncodedPolylineregistration pendingv0.1.1core ✓ full ✓ (44/44)

Performance

Median time, and ratio to the reference implementation measured in the same session. The spec's target is within 2×.

PortEncode 100k pointsDecode 100k points
ReferenceRust polyline 0.11.0: 0.892 msRust polyline 0.11.0: 0.643 ms
Nim1.645 ms (1.84×)0.802 ms (1.25×)
Zig1.308 ms (1.47×)0.642 ms (1.00×)
Julia1.466 ms (1.64×)0.816 ms (1.27×)

Spec and source