I have an encoded polyline string:
ivgfAw_}bNaAfMwBjZk@IUrCGlC?jBFjCDbAV~B^xBVdAJFbB~EpApClAzBfC~DfAbBvDxGFZvDxGtAzBpDbHp@hAbDdG|EhH@d@bEbGlDnFl\fi@lIfN~OlWvFbJ|BpDg@~x@bDdFtHfMvZ~f@hDvF|EzHhDxFxTj^lNlUjG~JjAnBxAzCx@rBjAvDx@rD\rBZpCRdCd@lIr@vJxApUVpEXxCj@bCp@bB@z@nAlBvAzAjA|@Aj@j@ZrBt@fDz@pDv@NDxA@|@b@z@f@v@j@nAnArGrH...
When I decode this using different tools, I get different results:
Google Polyline Utility (https://developers.google.com/maps/documentation/utilities/polylineutility ) → Decodes incorrectly
Google Routes API Polyline Decoder (https://developers.google.com/maps/documentation/routes/polylinedecoder ) → Decodes correctly (matches what I expect on the map)
Node.js using "@mapbox/polyline": "^1.2.1" → Gives the same result as the Polyline Utility, not the Routes API decoder.
import * as polyline from "@mapbox/polyline";
const coords = polyline.decode(encodedPolyline);
console.log(coords);
How can I correctly decode this polyline string in Node.js so that it matches the output of the Google Routes API polyline decoder? Is there a Node.js library (or implementation) that supports the newer encoding format Google uses?
This is Google Routes API Polyline Decoder(matches what I expect on the map)
This is incorrect
This happens because Google’s Routes API returns encoded polylines with escaped special characters in JSON responses, while @mapbox/polyline expects a raw, unescaped encoded polyline.
refer to this website:
https://developers.google.com/maps/documentation/utilities/polylineutility
Solution:
Unescape the encoded polyline before decoding it.
Use Google’s official polyline decoder (@googlemaps/polyline-codec) when working with Google APIs.
https://www.npmjs.com/package/@googlemaps/polyline-codec
let processedPolyline = encodedPolyline;
if (encodedPolyline.includes('\\')) {
try {
processedPolyline = JSON.parse(`"${encodedPolyline}"`);
} catch (err) {
console.error("Failed to unescape polyline:", err.message);
}
}
import { decode } from '@googlemaps/polyline-codec';
const coordinates = decode(processedPolyline);