Skip to content

Instantly share code, notes, and snippets.

@ajturner
Created December 8, 2010 16:17
Show Gist options
  • Save ajturner/733488 to your computer and use it in GitHub Desktop.
Save ajturner/733488 to your computer and use it in GitHub Desktop.
Decodes an encoded polyline
package com.maker.models
{
public class EncodedPolyline {
private static var instance:EncodedPolyline;
public function EncodedPolyline() {}
private static function _decodeLine(encoded:String):Array {
var len = encoded.length;
var index:Number = 0;
var points:Array = [];
var lat:Number = 0;
var lng:Number = 0;
while (index < len) {
var b:Number;
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;
points.push([lat * 1e-5, lng * 1e-5]);
}
return points;
}
// Decode an encoded levels string into a list of levels.
private static function _decodeLevels(encoded:String):Array {
var levels:Array = [];
for (var pointIndex = 0; pointIndex < encoded.length; ++pointIndex) {
var pointLevel = encoded.charCodeAt(pointIndex) - 63;
levels.push(pointLevel);
}
return levels;
}
// Decode the supplied encoded polyline and levels.
public static function decode(encodedPoints:String, encodedLevels:String) {
if (encodedPoints.length == 0 || encodedLevels.length == 0) { return; }
var enc_points:Array = _decodeLine(encodedPoints);
var enc_levels:Array = _decodeLevels(encodedLevels);
if (enc_points.length == 0 || enc_levels.length == 0) { return; }
// Point count and level count do not match
if (enc_points.length != enc_levels.length) { return; }
return {points: enc_points, levels: enc_levels};
}
} 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment