我正在为我的项目使用谷歌地图。当用户单击地图时,我显示一个标记。如何清除地图并在第二次单击时显示另一个标记?
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(32.1788385, 54.5177581);
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(map, event.latLng);
});
}
function placeMarker(map, location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
您需要将标记的引用保存在全局变量中。您还需要检查marker
的类型或将其包装在语句try-catch
。
const mapCanvas = document.getElementById("map");
var marker;
function initMap(){
var myCenter = new google.maps.LatLng(32.1788385, 54.5177581);
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(map, event.latLng);
});
}
function placeMarker(map, location) {
// Remove the previous marker
try {
marker.setMap(null)
} catch (e) {}
// Update the marker
marker = new google.maps.Marker({
position: location,
map: map
});
}
小提琴