Is there a way to constrain a marker so that when it is dragged, it moves along a given polyline in Leaflet JS?
In my page I have route that is presented as a Polyline and a Marker. I want to be able to drag the marker along the line to be able to display information about that part of the route.
Looking at the documentation here, it is not clear how I would go about that:
https://leafletjs.com/reference-1.6.0.html#marker
Note, I am using leaflet by means of vue2leaflet, though a solution that works for standard leaflet JS would be okay.
The vue 'template':
<l-map
class="leaftlet-map"
:zoom="map.zoom"
:center="map.center"
@update:zoom="zoomUpdated"
@update:center="centerUpdated"
@update:bounds="boundsUpdated"
>
<l-tile-layer :url="map.url" :attribution="map.attribution" />
<l-marker
v-if="positionMarker"
:lat-lng="positionMarker.center"
draggable
@move="markerMoved"
/>
<l-polyline
v-if="polyline.latlngs && polyline.latlngs.length > 0"
:lat-lngs="polyline.latlngs"
:color="polyline.color"
/>
</l-map>
Best Answer
This is a quick hack just to test the concept. Since
img
element is draggable by itself,L.divIcon
is used for draggable marker so thatdraggable="false"
attribute could be set. For keeping marker glued to polyline, polyline methodclosestLayerPoint
is used to locate closest point to mouse position on polyline.CSS:
HTML:
JS: