Search code examples
mapboxmapbox-gl-jsreact-map-glmaplibre-gl

How to compute the distance from the start of a polyline to a specific point on a map using maplibre?


I use maplibregl to display a map with a path (set of coordinates represented by a polyline). I want to compute the distance from the start of the polyline to any point hovered by the user, like on this screenshot:

enter image description here

What method can I use to get the polyline distance on mouseover?

Here is what I would like to do:

map.on('mousemove', 'lineLayerHover', (e) => {
   const lineLayerFeatures = map.queryRenderedFeatures(e.point).filter((feature) => {
      return feature.layer.id === 'lineLayerHover';
   });

   const distanceFromPolylineStart = lineLayerFeatures[0].geometry.distanceFromPolylineStart;

   console.log(distanceFromPolylineStart);
}

Solution

  • Thank to Anatolii's answer, here is the working solution using turf library:

    const traceLine = turf.lineString(routeCoordinates);
    const traceStartPoint = turf.point(routeCoordinates[0]);
    
    map.on('mousemove', 'traceLayerHover', (e) => {
    
       const hoveredPoint = turf.point(e.lngLat.toArray());
    
       const traceSliced = turf.lineSlice(traceStartPoint, hoveredPoint, traceLine);
       
    const distanceFromStart = turf.length(traceSliced, { units: 'kilometers' });
    
       console.log("distance from start", distanceFromStart);
    });