Created
November 17, 2015 14:39
-
-
Save grantges/7f8bf9d903e051b95c0a to your computer and use it in GitHub Desktop.
Polyline JavaScript Module
This file contains hidden or 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
var polyline = {}; | |
polyline.encodeCoordinate = function(coordinate) { | |
coordinate = Math.round(1e5 * coordinate); | |
coordinate <<= 1; | |
0 > coordinate && (coordinate = ~coordinate); | |
var output = ""; | |
while (coordinate >= 32) { | |
output += String.fromCharCode((32 | 31 & coordinate) + 63); | |
coordinate >>= 5; | |
} | |
output += String.fromCharCode(coordinate + 63); | |
return output; | |
}; | |
polyline.decodeCoordinate = function(str) { | |
for (var i = 0; i < str.length; i++) { | |
{ | |
str.charCodeAt(i) - 63; | |
} | |
result |= (31 & b) << shift; | |
shift += 5; | |
} | |
}; | |
polyline.decodeLine = function(str) { | |
var latitude_change, longitude_change, index = 0, lat = 0, lng = 0, coordinates = [], shift = 0, result = 0, byte = null; | |
while (index < str.length) { | |
byte = null; | |
shift = 0; | |
result = 0; | |
do { | |
byte = str.charCodeAt(index++) - 63; | |
result |= (31 & byte) << shift; | |
shift += 5; | |
} while (byte >= 32); | |
latitude_change = 1 & result ? ~(result >> 1) : result >> 1; | |
shift = result = 0; | |
do { | |
byte = str.charCodeAt(index++) - 63; | |
result |= (31 & byte) << shift; | |
shift += 5; | |
} while (byte >= 32); | |
longitude_change = 1 & result ? ~(result >> 1) : result >> 1; | |
lat += latitude_change; | |
lng += longitude_change; | |
var precision = Math.pow(10, -5); | |
coordinates.push({ | |
latitude: lat * precision, | |
longitude: lng * precision | |
}); | |
} | |
return coordinates; | |
}; | |
polyline.encodePoint = function(x, y) { | |
return this.encodeCoordinate(x) + this.encodeCoordinate(y); | |
}; | |
polyline.encodeLine = function(coordinates) { | |
var output = "", longitude = 0, latitude = 0; | |
for (var i = 0; i < coordinates.length; i++) { | |
var pt = [ coordinates[i][0], coordinates[i][1] ]; | |
(latitude || longitude) && (pt = [ pt[0] - latitude, pt[1] - longitude ]); | |
output += this.encodePoint(pt[0], pt[1]); | |
latitude = pt[0]; | |
longitude = pt[1]; | |
} | |
return output; | |
}; | |
void 0 !== typeof module && (module.exports = polyline); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment