[GIS] select two markers & draw line between them in leaflet

leafletopenstreetmap

I am very much new to leaflet.

I have multiple markers plotted on my map in leaflet.

now I have to draw line between two markers when I select them.

Can any one help in doing this.

Best Answer

So it seems to me all you have to do is take the two markers you have selected and grab their latlngs and add them to the polyline.

var latlngs = Array();

//Get latlng from first marker
latlngs.push(marker1.getLatLng());

//Get latlng from first marker
latlngs.push(marker2.getLatLng());

//You can just keep adding markers

//From documentation http://leafletjs.com/reference.html#polyline
// create a red polyline from an arrays of LatLng points
var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);

// zoom the map to the polyline
map.fitBounds(polyline.getBounds());

Edit

In case you are looking for a way to also get the selected markers. You will need to probably listen to the click event of each marker and add the markers to an array that contains your selected markers. You will just need to limit that array to two entries. This is not an optimal solution but should get you there and will allow you to easily extend if you want more than two markers.

Related Question