Created
May 30, 2012 15:17
-
-
Save abarth500/2836934 to your computer and use it in GitHub Desktop.
Generate Encoded Polyline Algorithm Format for Google Static Maps API (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Generate Encoded Polyline Algorithm Format for Google Static Maps API | |
// http://bit.ly/sw3deL (Japanese) | |
// http://bit.ly/tnKt4m (English) | |
function encodeGPolyline(path){ | |
var enc = ""; | |
var old = true; | |
for(c in path){ | |
var latlng = path[c]; | |
if(old === true){ | |
enc += encodeGPolylineNum(latlng[0])+ | |
encodeGPolylineNum(latlng[1]); | |
}else{ | |
enc += encodeGPolylineNum(latlng[0] - old[0])+ | |
encodeGPolylineNum(latlng[1] - old[1]); | |
} | |
old = latlng; | |
} | |
return enc; | |
} | |
function encodeGPolylineNum(num){ | |
var fu = false; | |
if(num < 0){ | |
fu = true; | |
} | |
//STEP2 | |
num = Math.round(num * 100000); | |
//STEP3 | |
//STEP4 | |
num = num << 1; | |
//STEP5 | |
if(fu){ | |
num = ~num; | |
} | |
//STEP6 - STEP7 | |
num = num.toString(2); | |
var n = []; | |
for(var c = 0; c < num.length; c++){ | |
n.push(num.charAt(c)); | |
} | |
num = []; | |
var nn = ""; | |
for(c=n.length-1;c >= 0;c--){ | |
nn = n[c] + nn; | |
if(nn.length == 5){ | |
num.push(nn); | |
nn = ""; | |
} | |
} | |
if(nn.length>0){ | |
nn = str_repeat("0",5 - nn.length) + nn; | |
num.push(nn); | |
} | |
//STEP8 - STEP9 - STEP10 - STEP11 | |
for(var c = 0;c < num.length;c++){ | |
if(c != num.length - 1){ | |
num[c] = String.fromCharCode(bindec(num[c]) + 32 + 63); | |
}else{ | |
num[c] = String.fromCharCode(bindec(num[c]) + 63); | |
} | |
} | |
return num.join(""); | |
} | |
function str_repeat(str, n){ | |
var ret = ""; | |
for (; n > 0; n >>>= 1, str += str) if (n & 1) ret += str; | |
return ret; | |
} | |
function bindec(binary_string) { | |
binary_string = (binary_string + '').replace(/[^01]/gi, ''); | |
return parseInt(binary_string, 2); | |
} | |
//例 | |
console.log(encodeGPolylineNum(-179.9832104)); | |
console.log(encodeGPolyline( | |
[ | |
[38.5,-120.2],[40.7,-120.95],[43.252,-126.453] | |
] | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment