Search code examples
reactjsgoogle-mapspolylinegoogle-polylinereact-google-maps-api

How to decode a polyline and draw it on a google map using "@react-google-maps/api"


I'm trying to use the @react-google-maps/api library to render a Google map on a react component and draw a polyline on the map, however, the polyline data that comes from the backend is encoded like this ...

@iBwCyC}FiA_BkAqBcDuD_GwF}KcJkTwQwVuSiPeNyJeIaEaEsZeWmMmKgg@cb@mToQqIqG_EiB}Aa@uCYyBI_CHeBVoI|B_Cn@qCb@eF^mAFcZEuEEqCM}BYqCaAuC_BcBqA}@iA{AwBaAmBgB}FyIaC{@mA_FsKuDgIwC_He@eA}JuTgS{c@yTcf@yLyVePm\\

How to decode that poline and draw it on the map using @react-google-maps/api?


Solution

  • @react-google-maps/api doesn't have a decoder, but you can use this package

    import { decode, encode } from "@googlemaps/polyline-codec";
    
    const encoded = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";
    console.log(decode(encoded, 5));
    // [
    //   [38.5, -120.2],
    //   [40.7, -120.95],
    //   [43.252, -126.453],
    // ]