Created
June 9, 2012 15:22
-
-
Save spion/2901417 to your computer and use it in GitHub Desktop.
Encodes / decodes a latlng object to 10 characters with 6 decimal (< 0.5 meter) precision
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
/** | |
* Encode/decode latlng | |
*/ | |
var latLngCoder = (function(map) { | |
map = map ? map : "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"; | |
var self = {}; | |
var encodenum = function(num, len) { | |
enc = []; | |
while (num > 0) { | |
enc.unshift(map[num % map.length]); | |
num = Math.floor(num / map.length); | |
} | |
while (len && enc.length < len--) enc.unshift("0"); | |
return enc.join(""); | |
} | |
var decodenum = function(code) { | |
dec = 0; | |
for (var k = 0; k < code.length; ++k) { | |
dec *= map.length; | |
dec += map.indexOf(code[k]); | |
} | |
return dec; | |
}; | |
/** | |
* Encode a latlng object | |
* @param c {lat:123.456789,lng:123.456789} | |
* @return "1234512345" | |
*/ | |
self.encode = function(c) { | |
return encodenum(Math.round(c.lat * 1000000), 5) + encodenum(Math.round(c.lng * 1000000), 5); | |
}; | |
/** | |
* Same as encode, only reversed | |
* @param c encode string | |
* @return object with lat and lng | |
*/ | |
self.decode = function(c) { | |
console.log(decodenum(c.substr(0,5))); | |
return {lat: decodenum(c.substr(0,5)) / 1000000, lng: decodenum(c.substr(5)) / 1000000}; | |
}; | |
return self; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment