node.jsgoogle-mapsroutesmapboxgoogle-polyline

Why does @mapbox/polyline decode differently than Google’s Routes API polyline decoder?


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:

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?

enter image description here

This is Google Routes API Polyline Decoder(matches what I expect on the map)

enter image description here

This is incorrect


Solution

  • 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:

    1. Unescape the encoded polyline before decoding it.

    2. 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);