Search code examples
reactjsmapboxmapbox-glreact-map-gl

Mapbox react - Display route with adjustments to nearest road using list of location points


I'm using mapbox with the wrapper react-map-gl. I'm trying to draw a route with my array of lat lang points, I found a partial solution from: https://github.com/visgl/react-map-gl/issues/591#issuecomment-454307294

enter image description here

The issue is that the presented route doesn't match the nearest road.

The current route is the green line and I'm trying to change it to be like the orange line


Solution

  • The best solution I have found is to use the react-map-gl with the deck.gl libraries.

    decl.gl, react-map-gl

    1. install the libraries

    2. Create a function using the Matching API from Mapbox:
      https://docs.mapbox.com/help/tutorials/get-started-map-matching-api/#add-the-map-matching-api Use the geometries=geojson option param (inside the URL of the matching call)

    3. return the geometry object from Matching API response (data.matchings[0].geometry)

    4. Create GeoJsonLayer with the new geometry object:

      const layerRoute = new GeoJsonLayer({
       id: "geojson-layer",
       data: getMatchingGeometry(),
       filled: true,
       stroked: false,
       extruded: true,
       pickable: true,
       lineJointRounded: true,
       getRadius: 50,
       getElevation: 30,
       lineWidthScale: 20,})
      
    5. Add the new layer to your map:

        return (
         <DeckGL layers={[layerRoute]} initialViewState={{ ...initialView }} controller={true}>
           <StaticMap
             height={height}
             width={width}
             mapStyle={mapboxstyle}
             mapboxApiAccessToken={API_TOKEN}
           />
         </DeckGL>)