Skip to content

Instantly share code, notes, and snippets.

@glenrobertson
Created November 13, 2012 03:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glenrobertson/4063726 to your computer and use it in GitHub Desktop.
Save glenrobertson/4063726 to your computer and use it in GitHub Desktop.
Handling for Google encoded polygons inside GeoJSON in Leaflet
// extend GeoJSON to handle google-encoded linestrings
// assumes that any array of coordinates that make up a linestring are replaced with the google encoded line string
L.extend(L.GeoJSON, {
// This function is from Google's polyline utility.
// Borrowed from: http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/decode.js
// Changed to return lng/lats instead of lat/lngs
decodeLine: function (encoded) {
var len = encoded.length;
var index = 0;
var array = [];
var lat = 0;
var lng = 0;
while (index < len) {
var b;
var shift = 0;
var result = 0;
do {
b = encoded.charCodeAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charCodeAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
array.push([lng * 1e-5, lat * 1e-5]);
}
return array;
},
coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
var latlng,
latlngs = [],
i, len;
for (i = 0, len = coords.length; i < len; i++) {
if (levelsDeep === 1 && typeof coords[i] === 'string') {
coords[i] = this.decodeLine(coords[i]);
}
latlng = levelsDeep ?
this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
this.coordsToLatLng(coords[i], reverse);
latlngs.push(latlng);
}
return latlngs;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment