UNPKG

mapbox

Version:
86 lines (74 loc) 2.25 kB
'use strict'; /* * polyline * * https://github.com/mapbox/polyline * * by John Firebaugh, Tom MacWright, and contributors * licensed under BSD 3-clause */ /* * Based off of [the offical Google document](https://developers.google.com/maps/documentation/utilities/polylinealgorithm) * * Some parts from [this implementation](http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoder.js) * by [Mark McClure](http://facstaff.unca.edu/mcmcclur/) * * @module polyline */ var polyline = {}; function encode(coordinate, factor) { coordinate = Math.round(coordinate * factor); coordinate <<= 1; if (coordinate < 0) { coordinate = ~coordinate; } var output = ''; while (coordinate >= 0x20) { output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63); coordinate >>= 5; } output += String.fromCharCode(coordinate + 63); return output; } /** * Encodes the given [latitude, longitude] coordinates array. * * @param {Array.<Array.<Number>>} coordinates * @param {Number} precision * @returns {String} */ polyline.encode = function(coordinates, precision) { if (!coordinates.length) { return ''; } var factor = Math.pow(10, precision || 5), output = encode(coordinates[0][0], factor) + encode(coordinates[0][1], factor); for (var i = 1; i < coordinates.length; i++) { var a = coordinates[i], b = coordinates[i - 1]; output += encode(a[0] - b[0], factor); output += encode(a[1] - b[1], factor); } return output; }; function flipped(coords) { var flipped = []; for (var i = 0; i < coords.length; i++) { flipped.push(coords[i].slice().reverse()); } return flipped; } /** * Encodes a GeoJSON LineString feature/geometry. * * @param {Object} geojson * @param {Number} precision * @returns {String} */ polyline.fromGeoJSON = function(geojson, precision) { if (geojson && geojson.type === 'Feature') { geojson = geojson.geometry; } if (!geojson || geojson.type !== 'LineString') { throw new Error('Input must be a GeoJSON LineString'); } return polyline.encode(flipped(geojson.coordinates), precision); }; module.exports = polyline;