Decoding Google Maps Encoded Polylines using PHP

I’ve talked about the Google Maps encoded polyline format before. While there’s some nice utilities for encoding polylines that take the work out of implementing it yourself, I couldn’t find many polyline decoders.

This made it somewhat tedious to decode them, as the only way to get the original list of points was to create a GPolyline and then pull out the points from that object. This is not ideal since the work must always be done on the client side with JavaScript and using Google Maps.

To solve this, I quickly ported the algorithm over to PHP from the JavaScript source. Please feel free to download/modify/use this script.

Since the encoded polyline format offers numerous benefits (and because I had data already stored in this format) I did not want to move away from it. At the same time, I needed access to the points for working with things like Google Static Maps, which curiously does not accept the encoded polyline format for displaying paths. (Probably to reduce resource usage on their end, since decoding takes CPU time)

Thankfully the polyline decoding algorithm was already available at Mark McClure’s site. I spent a few minutes understanding the process and porting it over to PHP. The source is attached above and is released under an MIT license. Basically, the only change I had to make was to use some PHP functions to convert characters to their ASCII code, since PHP doesn’t have a charCodeAt() function.

Please let me know if you find it to be useful.

2 Comments »

  1. dud, how i use this script? what variable do i parse

    grettings from chile

  2. The function is for taking an encoded polyline; it then returns an array of the points that make up the polyline.

    The polyline is an encoded string according to Google’s polyline algorithm.

    This is not a standalone script, it is merely a function that you can use in your own application.

Post a Comment

(required)

(will not be published) (required)

XHTML tags allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: rel="nofollow" will be added to all links in comments.