问题描述
我在点击时成功创建了一个标记,但是,使用以下代码,每次点击都会得到一个新标记,我只想要添加一个标记,如果有人多次点击,我希望它移动现有标记到新职位 任何人都可以帮忙这里是代码
I am successfully creating a marker on click however, using the following code, I get a new marker with every click, I only ever want one marker added and if someone clicks more than once I would like it to move the existing marker to the new position Can anyone help here is the code
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
var marker = new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
推荐答案
var marker;
function placeMarker(location) {
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
你必须一直在同一个标记上工作 - 不要创建新的.这里你有一个全局变量 marker
并且在 placeMarker
函数中你第一次将标记分配给这个变量.下次它检查标记已经存在,然后改变它的位置.
You have to work on the same marker all the time - do not create new ones.Here you have a global variable marker
and in placeMarker
function you assign marker to this variable first time. Next time it checks that marker exists already and then just changes its position.
这篇关于GoogleMaps v3 API 单击时仅创建 1 个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!