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

时间:2012-10-02 04:35:09

标签: javascript google-maps-api-3 geolocation 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
  });
}

2 个答案:

答案 0 :(得分: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); }
}

答案 1 :(得分: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);
    }
}