I'm making a web application using a leaflet map and I want the users to be able to put and remove markers as they wish but I can't figure out a way to do it.
The markers coordinates are stored in a database and when I load the page I use the coordinates (GET request) to put them on the map. And now I'm trying to find a way to delete a marker when users press a button located in the marker leaflet bindPopup.
$.ajax({
//GET REQUEST
})
.done(function( data ) {
for (i=0 ; i < data.length ; i++) {
// ......
var mp = new L.Marker([marker["lat"], marker["lng"]],{draggable:'true'});
mp.addTo(mymap);
mp.bindPopup('<button type="button" onclick="">Delete Marker</button>',{maxWidth: "auto"}).openPopup(); //Here i want to add a function that deletes a specific marker
markers.addLayer(mp);
The main problem I have is when I put the code in the onclick part of the button to delete the marker, it doesn't take the environment variable and therefore not the marker so I can't even send a DELETE request without the id.
Here is a working demo using document.createElement('button')
Note: bindPopup accepts HTMLElement
var mymap = L.map('Lmap').setView([41.349412, 2.151421], 10); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, fadeAnimation: false, zoomAnimation: false, markerZoomAnimation: false, attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', }).addTo(mymap); var mp = new L.Marker([41.349412, 2.151421], { draggable: 'true' }); mp.addTo(mymap); let btn = document.createElement('button'); btn.innerText = 'Delete Marker'; btn.onclick = function() { mymap.removeLayer(mp); } mp.bindPopup(btn, { maxWidth: 'auto' }).openPopup();
#Lmap { position: absolute; top: 35px; left: 0; width: 100%; height: 80% }
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script> <div id="Lmap"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.