Created
June 10, 2015 14:20
-
-
Save wboykinm/2eb37319ee5a08741550 to your computer and use it in GitHub Desktop.
Get a GeoJSON-friendly linestring from a Valhalla/OSRM route request
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
// Get a GeoJSON-friendly linestring from a Valhalla/OSRM route request | |
// Adapted from | |
// https://github.com/DennisSchiefer/Project-OSRM-Web/blob/develop/WebContent/routing/OSRM.RoutingGeometry.js | |
// Usage: decode(<"shape" object>, 6) //(precision = 6 seems legit) | |
var decode = function(encoded, precision) { | |
var len = encoded.length, | |
index = 0, | |
lat = 0, | |
lng = 0, | |
array = []; | |
precision = Math.pow(10, -precision); | |
while (index < len) { | |
var b, | |
shift = 0, | |
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; | |
//coordinate order for geojson: | |
array.push([lng * precision, lat * precision]); | |
} | |
return array; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment