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

标签 javascript google-maps-api-3 geolocation google-maps-markers

我有以下代码,允许用户点击 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/

相关文章:

google-app-engine - Google App Engine 地理散列

javascript - 正则表达式匹配本地 Markdown 链接

google-maps - 如何从 Google Maps API v3 中删除国际日期变更线 (IDL) 和赤道?

javascript - 在谷歌地图上找到最近的引脚

java - 计算地理点之间角度的正确方法

javascript - 四舍五入的纬度和经度以在 Google map 中显示大致位置

Javascript pagination - 自动切换时间间隔

javascript - 在 Javascript 中 sleep ()

javascript - 如何禁止取消选中复选框元素?

javascript - Google Map v3 - getPosition 不是函数