且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除先前的标记并在更新的 lat lng 中添加标记

更新时间:2023-12-03 18:24:16

您有两个选择,都涉及在 displayLocation 函数之外保留对标记的引用:

You have two options, both involve keeping a reference to the marker outside of the displayLocation function:

  1. 使用引用移动现有标记

var marker;
function displayLocation(location) {
  console.log(location.lat)
    var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng));
    if (marker && marker.setPosition) {
      // if the marker already exists, move it (set its position)
      marker.setPosition(location);
    } else {
      // create a new marker, keeping a reference
      marker = new google.maps.Marker({
        map: map, 
        position: position,
        title: 'test!'
      });
    }
}

  1. 从地图中移除现有标记并创建一个新标记

var marker;
function displayLocation(location) {
  console.log(location.lat)
    var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng));
    if (marker && marker.setMap) {
      // if the marker already exists, remove it from the map
      marker.setMap(null);
    }
    // create a new marker, keeping a reference
    marker = new google.maps.Marker({
      map: map, 
      position: position,
      title: 'test!'
    });
}