javascript - LeafletJS,如何删除绑定(bind)弹出窗口中带有按钮的标记

标签 javascript leaflet openstreetmap

我正在使用传单 map 制作一个网络应用程序,我希望用户能够根据自己的意愿放置和删除标记,但我不知道如何做到这一点。

标记坐标存储在数据库中,当我加载页面时,我使用坐标(GET 请求)将它们放在 map 上。现在,我正在尝试找到一种方法,当用户按下标记传单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);

我遇到的主要问题是,当我将代码放在按钮的 onclick 部分来删除标记时,它不使用环境变量,因此不使用标记,因此我什至无法发送 DELETE 请求ID。

最佳答案

这是一个使用 document.createElement('button') 的工作演示

注意: 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: '&copy; <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>

关于javascript - LeafletJS,如何删除绑定(bind)弹出窗口中带有按钮的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57096346/

相关文章:

r - 在R中: using leaflet - create an iconList with many icons programmatically

postgresql - Osm2pgsql 由于错误 : Cannot detect file format 而失败

java - jxmapkit 点击事件返回不正确的经纬度

r - R 中的传单 : SetView based on range of latitude and longitude from dataset

javascript - ReactJs 将值传递给另一个 js 文件中的函数

javascript - 异步悖论BackboneJS

javascript - ng标签输入不允许在文本框中输入两次相同的文本

javascript - 如何在 react 功能组件中使用动画 svg?

d3.js - d3 和 Leaflet 之间的 GeoJSON 映射差异

javascript - “GeoJSON 对象无效。”使用传单和传单-ajax