Google Maps Encoded Polylines

Update 6/30/07: Fixed links to so that it’s actually accessible.
Update 7/15/08: Fixed links to 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 GitHub project instead:

glineenc on GitHub

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.

12 thoughts on “Google Maps Encoded Polylines

  1. Now that’s bloody awesome. I’ve got a site working on right now with a potential use, will report back if it comes in handy.

  2. 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?

  3. Hi!

    Perfect tool for my app – i was not too eager to implement the encoding-algorithm on my own when i first saw it, but thx to you i don’t have too :-)
    Could you add a license and version header plz?


  4. 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.

    Other than that, works a charm!
    R. Taylor

  5. i.ll be back details comments after i applied this, and Thank you so much..

Comments are closed.