0

I am working with leaflet api where user can put markers on map. I have made a custom button for putting marker.

I am willing to draw line between those markers i.e. using L.polylines() but as I am new to javascript and leaflet I can't understand how to pass those latlng point to array which will later be used in these functions. For initial working I have passed static coordinates(working as req).

L.easyButton('fa-link', function () {

var secureThisArea = [[-81, 100.75], [-76.50, 245.75], [-145.50, 184.25], [-128, 311.75]];

    map.on('click', function fencePlace(e) {

    L.marker([-81, 100.75], { icon: fenceIcon, draggable: true }).bindPopup("this is first").addTo(map);
    L.marker([-76.50, 245.75], { icon: fenceIcon, draggable: true }).bindPopup("this is second").addTo(map);
    L.marker([-145.50, 184.25], { icon: fenceIcon, draggable: true }).bindPopup("this is third").addTo(map);
    L.marker([-128, 311.75], { icon: fenceIcon, draggable: true }).bindPopup("this is fourth").addTo(map);
    L.polyline(secureThisArea).addTo(map);

});
                }).addTo(map);
user229044
  • 232,980
  • 40
  • 330
  • 338
Suhail Mumtaz Awan
  • 3,295
  • 8
  • 43
  • 77

2 Answers2

2

Adding another value to an array is easy, e.g.:

secureThisArea.push([-81, 100.75]);

You can find more details (also about anything else JavaScript related) at Mozilla Developer Network.

If you want to use the coordinates from the marker objects, you can get those with:

var myMarker = L.marker([-81, 100.75], { icon: fenceIcon, draggable: true }),
    latLng = null;

latLng = myMarker.getLatLng();

Also take a look at the Leaflet documentation.

RhinoDevel
  • 712
  • 1
  • 12
  • 25
2

If i understand you correctly you want to create markers on click and connect them via polylines. That's easy to do, in code with comments to explain:

// Create new empty polyline and add it to the map
var polyline = new L.Polyline([]).addTo(map);

// Handle map click event
map.on('click', function(event) {

    // New marker on coordinate, add it to the map
    new L.Marker(event.latlng).addTo(map);

    // Add coordinate to the polyline
    polyline.addLatLng(event.latlng);

});

Now afterwards if you want to get all the coordinates added to the polyline you can use the getLatLngs method of L.Polyline which returns an array of L.LatLng objects.

Reference: http://leafletjs.com/reference.html#polyline

Example: http://plnkr.co/edit/h7aMwc?p=preview

iH8
  • 27,722
  • 4
  • 67
  • 76
  • thanks for answer, its the perfect solution for my understanding, i wish i can give more than upvote,,,, – Suhail Mumtaz Awan Sep 14 '15 at 12:54
  • 1
    No thanks, always welcome. If it's a better answer to your question than the one you've accepted you can always accept another instead. See: http://stackoverflow.com/help/accepted-answer – iH8 Sep 14 '15 at 12:58