gpt4 book ai didi

javascript - 允许用户一次只创建一个 Google map 标记

转载 作者:行者123 更新时间:2023-12-04 00:03:09 25 4
gpt4 key购买 nike

我有以下代码,允许用户点击 map 上的某个地方,并记录他们点击的任何地方的 GPS 位置。它在后端正常工作,但只要用户点击多次,它就会在 map 上留下多个标记。它始终保留最后一个位置,因此它可以正常工作,但对于不知道后端发生了什么的用户来说有点困惑。有什么我可以做的小技巧,以便每当用户点击创建新标记时,旧标记就会被删除吗?

代码:

    var map;
var GPSlocation;


function initialize() {
var haightAshbury = new google.maps.LatLng(37.7699298, -93.4469157);
var mapOptions = {
zoom: 4,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);

google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}

function addMarker(location) {
//I save the location right here
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}

最佳答案

只需使用 google.maps.Marker 实例的 setPosition 方法:

var map,
GPSlocation,
marker; // <-- Added

// ... snip ...

function addMarker(location) {
// ... snip ...
if (!marker) {
// Create the marker if it doesn't exist
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Otherwise, simply update its location on the map.
else { marker.setPosition(location); }
}

关于javascript - 允许用户一次只创建一个 Google map 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12684589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com