From 69ff2e20ec7ad4fef6f676e94e7134c5fdecca7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maximilian=20Kr=C3=B6g?= Date: Thu, 6 Apr 2023 01:05:46 +0200 Subject: [PATCH] Round each coordinate only once --- src/polyline.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/polyline.js b/src/polyline.js index 3aba1c6..d779397 100644 --- a/src/polyline.js +++ b/src/polyline.js @@ -13,14 +13,11 @@ var polyline = {}; function py2_round(value) { // Google's polyline algorithm uses the same rounding strategy as Python 2, which is different from JS for negative values - return Math.floor(Math.abs(value) + 0.5) * (value >= 0 ? 1 : -1); + return value < 0 ? Math.ceil(value - 0.5) : Math.round(value); } -function encode(current, previous, factor) { - current = py2_round(current * factor); - previous = py2_round(previous * factor); - var coordinate = current - previous; - coordinate <<= 1; +function encode(current, previous) { + var coordinate = (current - previous) << 1; if (current - previous < 0) { coordinate = ~coordinate; } @@ -99,15 +96,18 @@ polyline.decode = function(str, precision) { * @returns {String} */ polyline.encode = function(coordinates, precision) { - if (!coordinates.length) { return ''; } - var factor = Math.pow(10, Number.isInteger(precision) ? precision : 5), - output = encode(coordinates[0][0], 0, factor) + encode(coordinates[0][1], 0, 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); + output = '', + bLat = 0, + bLon = 0; + + for (var i = 0; i < coordinates.length; i++) { + var a = coordinates[i]; + var aLat = py2_round(a[0] * factor); + var aLon = py2_round(a[1] * factor); + output += encode(aLat, bLat) + encode(aLon, bLon); + bLat = aLat; + bLon = aLon; } return output;