Google Static Maps: polyline encoding with Javascript

Functions

function createEncodings(coords) {
	var i = 0;
 
	var plat = 0;
	var plng = 0;
 
	var encoded_points = "";
 
	for(i = 0; i < coords.length; ++i) {
	    var lat = coords[i][0];				
		var lng = coords[i][1];		
 
		encoded_points += encodePoint(plat, plng, lat, lng);
 
	    plat = lat;
	    plng = lng;
	}
 
	// close polyline
	encoded_points += encodePoint(plat, plng, coords[0][0], coords[0][1]);
 
	return encoded_points;
}
 
function encodePoint(plat, plng, lat, lng) {
	var late5 = Math.round(lat * 1e5);
    var plate5 = Math.round(plat * 1e5)    
 
	var lnge5 = Math.round(lng * 1e5);
    var plnge5 = Math.round(plng * 1e5)
 
	dlng = lnge5 - plnge5;
	dlat = late5 - plate5;
 
    return encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
}
 
function encodeSignedNumber(num) {
  var sgn_num = num << 1;
 
  if (num < 0) {
    sgn_num = ~(sgn_num);
  }
 
  return(encodeNumber(sgn_num));
}
 
function encodeNumber(num) {
  var encodeString = "";
 
  while (num >= 0x20) {
    encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
    num >>= 5;
  }
 
  encodeString += (String.fromCharCode(num + 63));
  return encodeString;
}

Use example

// define polyline
var points = new Array();
 
points[0] = [25.774252, -80.190262];
points[1] = [18.466465, -66.118292];
points[2] = [32.321384, -64.75737];
 
// encode polyline
var encoded = createEncodings(points);

Live demo

Feedback

I used this code and it saved me a lot of headache. Thanks!
Eric Toupin
Oct 31, 2010
#1
After a few hours of research I was about to give up, and just in the last moment I saw this, I tried it, and It worked perfect for me! Thanks so much!
Carlos
Jan 13, 2011
#2
Thanks a lot. Greate help.
Just short question.

// close polyline
encoded_points += encodePoint(plat, plng, coords[0][0], coords[0][1]);
I think that the above line does not need.
Passby
Nov 4, 2011
#3
thank you very much. god bless you :)
vermouth
Dec 20, 2012
#4
This is GREAT!

Thank you very, very much!

Works perfect for me! \o/
Diego
May 17, 2013
#5
I was about to give up my searhing for EXACTLY this thing online.
When I clicked my last link and ended up here. I was like Yeah. I found it.

Thanks thanks thanks

WackyApps
Dec 26, 2013
#6
Cannot thank you enough for this - after months of coding this was one of the last things I had to figure out and you saved me days of frustration.

Legend.
FizzleSticks
Mar 14, 2016
#7