我在页面加载时加载了一个标记,我希望在用户单击地图时删除该标记并添加另一个标记,但是它不起作用。
这就是我尝试过的
var map = L.map('map').setView([35.79, 51.47], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <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);
});
这是一个工作示例 https://jsfiddle.net/ky0xrpe9/
答案 0 :(得分:1)
theMarkerLatLng = { lat: 35.810992207495154, lng: 51.45223617553712};
theMarker = L.marker(theMarkerLatLng, {
draggable: true,
title: "Resource location",
alt: "Resource Location",
riseOnHover: true
}).addTo(map)