Is there a way to add "Snap to road" in react leaflet?

1.2k views Asked by At

I am looking for way to make all the polylines between each of my markers "snap to road" rather than being a direct line drawn between point a and b. So between any two points, i would like the points to be automatically placed on the closest road (if the mark is not placed on a road) and would like a polyline produced that is along the shortest road route between the two points. I’ve just started looking into the google maps API and it seems like they have the feature, but I don't want to have to change everything I have already. Here's my code.

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { MapContainer, TileLayer, Polyline } from "react-leaflet";
import "../styles/Map.css";
import AddMarkers from "./AddMarkers";

const Map = () => {
  const markers = useSelector((state) => state.markers);

  return (
    <div className="leaflet-container">
      <MapContainer
        center={[50.868031999999996, -9]}
        zoom={20}
        scrollWheelZoom={true}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <AddMarkers />
        {markers.length > 1 && (
          <Polyline
            positions={markers.map((marker) => {
              return [marker.lat, marker.lng];
            })}
          />
        )}
      </MapContainer>
    </div>
  );
};

export default Map;

1

There are 1 answers

2
suther On

It seems that you might searching for: https://github.com/makinacorpus/Leaflet.Snap

This should make it possible to enables snapping of draggable markers to polylines and other layers. The Demo-Link in this Page is broken, but it's seems to be well documented in the GitHub-Page, how to use. I think you'll need to use the section Leaflet.Draw for your implementation.

Wish you good luck with getting your Map to work like expected.