Anas.S
Anas.S

Reputation: 305

How to click a point and save its coordinates in Leaflet?

I have a couple of points visualized in a leaflet map as you can see in the figure:

enter image description here

I would like to add a function that selects as many of these points I want and save their geometry. I have done something similar to show the provider and the battery attributes of the selected markers:

function onEachFeature ( feature , layer )
    {
        var popupContent = "Provider: " + feature.properties.provider + '</b><br/>' + "Battery level: " + feature.properties.battery;
        layer.bindPopup(popupContent);
    }

I would like some guidelines on how to create a click event when I click on the markers and how I can save the geometry (maybe to an array).

I know the question is kinda general but I would really appreciate any help since its my first project using html,javascript and css.

Thank you in advance!

Upvotes: 0

Views: 1425

Answers (1)

Falke Design
Falke Design

Reputation: 11338

Add a click listener to the marker. In the click listener you can use the unique leaflet id of the marker to add and remove them from the list:

var selectedData = {};
function onEachFeature ( feature , layer )
    {
        var popupContent = "Provider: " + feature.properties.provider + '</b><br/>' + "Battery level: " + feature.properties.battery;
        layer.bindPopup(popupContent);
        layer.on('click',(e)=>{
            var marker = e.target;
            if(selectedData[marker._leaflet_id]){
               delete selectedData[marker._leaflet_id];
            } else {
               selectedData[marker._leaflet_id] = marker;
            }
        })
    }

To get all markers in the list use:

for(var id in selectedData){
   var marker = selectedData[id];
   console.log(marker.getLatLng())
   console.log(marker.toGeoJSON())
}

Upvotes: 1

Related Questions