Skip to content

Instantly share code, notes, and snippets.

@grantges
Created November 17, 2015 14:39
Show Gist options
  • Select an option

  • Save grantges/7f8bf9d903e051b95c0a to your computer and use it in GitHub Desktop.

Select an option

Save grantges/7f8bf9d903e051b95c0a to your computer and use it in GitHub Desktop.

Revisions

  1. Bert Grantges created this gist Nov 17, 2015.
    72 changes: 72 additions & 0 deletions polyline.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    var polyline = {};

    polyline.encodeCoordinate = function(coordinate) {
    coordinate = Math.round(1e5 * coordinate);
    coordinate <<= 1;
    0 > coordinate && (coordinate = ~coordinate);
    var output = "";
    while (coordinate >= 32) {
    output += String.fromCharCode((32 | 31 & coordinate) + 63);
    coordinate >>= 5;
    }
    output += String.fromCharCode(coordinate + 63);
    return output;
    };

    polyline.decodeCoordinate = function(str) {
    for (var i = 0; i < str.length; i++) {
    {
    str.charCodeAt(i) - 63;
    }
    result |= (31 & b) << shift;
    shift += 5;
    }
    };

    polyline.decodeLine = function(str) {
    var latitude_change, longitude_change, index = 0, lat = 0, lng = 0, coordinates = [], shift = 0, result = 0, byte = null;
    while (index < str.length) {
    byte = null;
    shift = 0;
    result = 0;
    do {
    byte = str.charCodeAt(index++) - 63;
    result |= (31 & byte) << shift;
    shift += 5;
    } while (byte >= 32);
    latitude_change = 1 & result ? ~(result >> 1) : result >> 1;
    shift = result = 0;
    do {
    byte = str.charCodeAt(index++) - 63;
    result |= (31 & byte) << shift;
    shift += 5;
    } while (byte >= 32);
    longitude_change = 1 & result ? ~(result >> 1) : result >> 1;
    lat += latitude_change;
    lng += longitude_change;
    var precision = Math.pow(10, -5);
    coordinates.push({
    latitude: lat * precision,
    longitude: lng * precision
    });
    }
    return coordinates;
    };

    polyline.encodePoint = function(x, y) {
    return this.encodeCoordinate(x) + this.encodeCoordinate(y);
    };

    polyline.encodeLine = function(coordinates) {
    var output = "", longitude = 0, latitude = 0;
    for (var i = 0; i < coordinates.length; i++) {
    var pt = [ coordinates[i][0], coordinates[i][1] ];
    (latitude || longitude) && (pt = [ pt[0] - latitude, pt[1] - longitude ]);
    output += this.encodePoint(pt[0], pt[1]);
    latitude = pt[0];
    longitude = pt[1];
    }
    return output;
    };

    void 0 !== typeof module && (module.exports = polyline);