允许用户一次只创建一个Google地图标记

exp*_*yre 2 javascript geolocation google-maps-api-3 google-maps-markers

我有以下代码,允许用户点击地图上的某个位置,并记录他们点击的位置的GPS位置.它在后端正常工作,但每当用户点击多次时,它会在地图上留下多个标记.它始终保留最后一个位置,因此它可以工作,但对于不知道后端发生了什么的用户来说有点混乱.是否有一些小技巧可以做到这一点,以便每当用户点击创建一个新标记时,旧的标记被删除?

码:

    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
  });
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*ira 6

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

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); }
}
Run Code Online (Sandbox Code Playgroud)