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:

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):

12 thoughts on “Google Maps Encoded Polylines”

Could you save even more on-the-fly processing time by pre-encoding the latitude and longitude of every node in your database? Then your routing process would just lookup the stored ascii string representing the lat/long for each node in the route. Or maybe thatâ€™s how youâ€™re already using it?

Just a heads up that you need to escape slashes in the encoded strings.

I had a large number of points to display and the encoded string had several back slashes in it. Google maps just died with a “a is undefined” error and it took me a long time to figure out that I needed to escape the slashes.

You should just be able to do a replace(‘\\’,’\\\\’) on the encoded string before returning it.