Leaflet - How to combine a marker and a polyline with drag and drop

I have a project with leafletJS. For example, I have 2 points (A, B) on the map. I show it as 2 markers. I have to draw a polyline from A to B. I have moved marker A, and I want the head of the polyline of marker A to correspond to marker A (moved after marker A). How can i do this? Sorry for my bad english. Thank you very much.

Truong M.

+5
source share
1 answer

Given the following L.Latlng 's, L.Marker and L.Polyline :

 var a = new L.LatLng(-45, -90), b = new L.LatLng(45, 0), c = new L.LatLng(-45, 90); var marker_a = new L.Marker(a, {draggable: true}).addTo(map), marker_b = new L.Marker(b, {draggable: true}).addTo(map), marker_c = new L.Marker(c, {draggable: true}).addTo(map); var polyline = new L.Polyline([a, b, c]).addTo(map); 

You will need to attach eventlisteners and callbacks to your L.Marker . You can automate this, but I keep it simple:

 marker_a .on('dragstart', dragStartHandler) .on('drag', dragHandler) .on('dragend', dragEndHandler); marker_b .on('dragstart', dragStartHandler) .on('drag', dragHandler) .on('dragend', dragEndHandler); marker_c .on('dragstart', dragStartHandler) .on('drag', dragHandler) .on('dragend', dragEndHandler); 

Now on dragstart you will need to find latlng from the polyline that matches your latlng marker and save it in your marker instance so you can use it later:

 function dragStartHandler (e) { // Get the polyline latlngs var latlngs = polyline.getLatLngs(), // Get the marker start latlng latlng = this.getLatLng(); // Iterate the polyline latlngs for (var i = 0; i < latlngs.length; i++) { // Compare each to the marker latlng if (latlng.equals(latlngs[i])) { // If equals store key in marker instance this.polylineLatlng = i; } } } 

Now you know the key for the latlng polyline, which you can change when dragging the marker onto dragevent:

 function dragHandler (e) { // Get the polyline latlngs var latlngs = polyline.getLatLngs(), // Get the marker current latlng latlng = this.getLatLng(); // Replace the old latlng with the new latlngs.splice(this.polylineLatlng, 1, latlng); // Update the polyline with the new latlngs polyline.setLatLngs(latlngs); } 

Just to be clean and tidy, delete the saved key on dragend:

 function dragEndHandler (e) { // Delete key from marker instance delete this.polylineLatlng; } 

What is it. Here is a working example on Plunker: http://embed.plnkr.co/SJRec3/preview

+8
source

Source: https://habr.com/ru/post/1235161/


All Articles