Encoded polylines
A route or shape is naturally a list of coordinates, but sending hundreds of floating-point numbers is wasteful. The Google encoded polyline format squeezes that path into a single short string that map and routing APIs understand directly. A three-point path that would otherwise consume over 50 characters of JSON can compress to as few as 20 ASCII characters.
How the algorithm works, step by step
- Scale and round: Multiply each latitude and longitude by 10^precision (100,000 for precision 5, 1,000,000 for precision 6) and round to an integer.
- Take deltas: Store the difference from the previous point. The first point uses zero as the previous value, so the string is self-contained.
- Sign-encode: Left-shift each delta by one bit. If the value is negative, invert all bits. This packs the sign into the lowest bit.
- Chunk and emit: Split the result into 5-bit groups, OR each chunk with 0x20 if more chunks follow, then add 63 to land in printable ASCII.
[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]
-> _p~iF~ps|U_ulLnnqC_mqNvxq`@
The first point is encoded as a delta from zero, so the string is fully self-contained. Each subsequent point only records how far it moved from the last one, which is why consecutive GPS points — rarely more than a few hundred metres apart — compress so effectively.
Choosing between precision 5 and precision 6
| Setting | Multiplier | Resolution | Use when |
|---|---|---|---|
| Precision 5 | 100,000 | ~1 metre | Google Maps, Google Directions API, most web maps |
| Precision 6 | 1,000,000 | ~0.1 metre | OSRM, Valhalla, Mapbox Directions, high-accuracy GPS tracks |
Mixing precision at encode and decode produces coordinates scaled by 10×, which looks like all points jumping to the wrong location — it is the most common polyline debugging mistake.
Practical tips
- Order matters: The encoding is delta-based, so the coordinates must be in path order. Reversing the array produces a valid but backwards route.
- Round-tripping: Feed the encoded string into a decoder at the same precision and you recover the original points, subject only to rounding at the chosen precision.
- Coordinates per line: This encoder accepts one
lat, lngpair per line; commas and spaces between the two numbers are both recognised. - API use: Once encoded, drop the string directly into the
polylineparameter of a Google Maps Static API or Directions API call without any additional serialisation.