Last active
August 29, 2015 14:09
-
-
Save nicopace/82b568a29d994ed32c6e to your computer and use it in GitHub Desktop.
Testing OTP polyline decoding in javascript
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
<html> | |
<head> | |
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> | |
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" /> | |
<style> | |
#map { height: 500px; } | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<script> | |
// create a map in the "map" div, set the view to a given place and zoom | |
var map = L.map('map').setView([-38.7096, -62.2760], 15); | |
// add an OpenStreetMap tile layer | |
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { | |
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' | |
}).addTo(map); | |
var decodePolyline = function(polyline) { | |
var currentPosition = 0; | |
var currentLat = 0; | |
var currentLng = 0; | |
var dataLength = polyline.length; | |
var polylineLatLngs = new Array(); | |
while (currentPosition < dataLength) { | |
var shift = 0; | |
var result = 0; | |
var byte; | |
do { | |
byte = polyline.charCodeAt(currentPosition++) - 63; | |
result |= (byte & 0x1f) << shift; | |
shift += 5; | |
} while (byte >= 0x20); | |
var deltaLat = ((result & 1) ? ~(result >> 1) : (result >> 1)); | |
currentLat += deltaLat; | |
shift = 0; | |
result = 0; | |
do { | |
byte = polyline.charCodeAt(currentPosition++) - 63; | |
result |= (byte & 0x1f) << shift; | |
shift += 5; | |
} while (byte >= 0x20); | |
var deltLng = ((result & 1) ? ~(result >> 1) : (result >> 1)); | |
currentLng += deltLng; | |
polylineLatLngs.push(new L.LatLng(currentLat * 0.00001, currentLng * 0.00001)); | |
} | |
return polylineLatLngs; | |
}; | |
points = "rkhkFzla{JxDqFvDqFvDoFxDqFvDqFvDqFvDqFaEwFcE{FaEyFaEwFxFkIvFgIbBaIjMR?uLqC{DqCyDqCyDPaIrC_EpCaErCaEdCdDdCdD"; | |
pointslist = decodePolyline(points); | |
L.polyline(pointslist).addTo(map); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment