Leaflet 如何移除加载、传单中添加的标记

Leaflet 如何移除加载、传单中添加的标记,leaflet,Leaflet,我在加载页面时加载一个标记,我希望当用户单击地图时,删除这个标记并添加另一个标记,但它不起作用 这就是我试过的 var map = L.map('map').setView([35.79, 51.47], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetma

我在加载页面时加载一个标记,我希望当用户单击地图时,删除这个标记并添加另一个标记,但它不起作用

这就是我试过的

 var map = L.map('map').setView([35.79, 51.47], 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);


    theMarker = { lat: 35.810992207495154, lng: 51.45223617553712};
    L.marker(theMarker, {
        draggable: true,
        title: "Resource location",
        alt: "Resource Location",
        riseOnHover: true
    }).addTo(map)
    map.on('click', function (e) {
        lat = e.latlng.lat;
        lon = e.latlng.lng;

        alert("You clicked the map at LAT: " + lat + " and LONG: " + lon);
        //Clear existing marker, 

        if (theMarker != undefined) {
            map.removeLayer(theMarker);
        };

        //Add a marker to show where you clicked.
        theMarker = L.marker([lat, lon]).addTo(map);
    });
var-map=L.map('map').setView([35.79,51.47],13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'{
属性:“©;贡献者”
}).addTo(地图);
市场价格={lat:35.810992207495154,lng:51.45223617553712};
L.马克(marker{
真的,
标题:“资源位置”,
alt:“资源位置”,
riseOnHover:正确
}).addTo(地图)
地图上('点击')功能(e){
lat=e.latlng.lat;
lon=e.latlng.lng;
警报(“您在LAT:+LAT+”和LONG:+lon处单击了地图);
//清除现有标记,
如果(市场!=未定义){
地图移除层(市场);
};
//添加标记以显示单击的位置。
标记器=L.标记器([lat,lon])。添加到(map);
});
这是一个工作样本

    theMarkerLatLng = { lat: 35.810992207495154, lng: 51.45223617553712};
    theMarker = L.marker(theMarkerLatLng, {
        draggable: true,
        title: "Resource location",
        alt: "Resource Location",
        riseOnHover: true
    }).addTo(map)