Tag Archives: google maps

Google Maps Encoded Polylines

Update 6/30/07: Fixed links to glineenc.py so that it’s actually accessible.
Update 7/15/08: Fixed links to glineenc.py again because of change to HTTPS on Trac site.

Here’s some Python code (complete with unit and doc tests) for converting a series of latitude/longitude points (i.e., a polyline) to the Base64 encoding that Google Maps understands. It’s particularly useful for long and/or complicated lines.

It’s based on the algorithm listed here and the JavaScript code here [page disappeared].

This site gives some more insight into it and has a pretty cool example of a fractal line here.

Here’s the code:

Previously, I had pasted the Python code right into this article, but I recently made a bunch of revisions and it was way too long. Here’s a link to the Bitbucket project instead:

glineenc on Bitbucket

Please note that this code is still in somewhat of a rough state. I have plans to polish and package it up, but for now, I’m using it as is and it’s working quite well (you’ll have to be patient to click that link as it takes ~20-30 seconds to generate the route, even though the line drawing itself is almost instantaneous).

JavaScript that uses results from `glineenc` looks something like this (assuming you’ve returned some JSON, say, with `encoded_points` and `encoded_lines` keys):

 map.addOverlay(new GPolyline.fromEncoded({ color: "#0000ff", weight: 4, opacity: 0.8, points: result.encoded_points, levels: result.encoded_levels, zoomFactor: 32, numLevels: 4 })); 

`points` is the encoded lat/long points. `levels` indicates which zoom levels each point should displayed at; there is one character per point. See the links above for a more complete explanation.