Skip to content

Instantly share code, notes, and snippets.

@dgngulcan
Last active June 27, 2018 17:41
Show Gist options
  • Save dgngulcan/1492b0fb251363d1478d89e9ca8fa356 to your computer and use it in GitHub Desktop.
Save dgngulcan/1492b0fb251363d1478d89e9ca8fa356 to your computer and use it in GitHub Desktop.
Function to decode an encoded polyline for JavaScript
function decodePolyline(encoded) {
var points = []
var index = 0,
len = encoded.length;
var lat = 0,
lng = 0;
while (index < len) {
var b, shift = 0,
result = 0;
do {
b = encoded.charAt(index++).charCodeAt(0) - 63; //finds ascii //and substract it by 63
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
var dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++).charCodeAt(0) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
var dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
points.push({
latitude: (lat / 1E6),
longitude: (lng / 1E6)
})
}
return points
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment