2

我有以下代码,允许用户单击地图上的某个位置,并记录他们单击的任何位置的 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
  });
}
4

2 回答 2

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); }
}
于 2012-10-02T04:41:04.077 回答
3

通过在函数外部声明标记使标记成为全局变量:

var marker;
function addMarker(location) {
    GPSlocation = location;
    document.getElementById("GPSlocation").value = GPSlocation;
    marker = new google.maps.Marker({
        position: location,
        map: map
    });
}

您还可以通过仅更新标记的位置而不是创建新对象来提高效率:

var marker;
function addMarker(location) {
    GPSlocation = location;
    document.getElementById("GPSlocation").value = GPSlocation;
    if (!marker) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    } else {
        marker.setPosition(location);
    }
}
于 2012-10-02T04:40:19.580 回答