如何用最后一次点击替换地点标记?

how to replace place marker with last click?

JS

var map;

function initialize()
{
    var myCenter=new google.maps.LatLng(13.001294, 77.661736);
    var mapProp = {
  center:myCenter,
  zoom:15,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });
}

function placeMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map,
  });
  document.getElementById("latt").innerHTML = location.lat();
  document.getElementById("long").innerHTML = location.lng();

}

google.maps.event.addDomListener(window, 'load', initialize);

HTML

<div id="googleMap" style="width:500px;height:380px;"></div>
<p id="latt"></p>
<p id="long"></p>

这里当我们点击一​​张以上的地图时,会出现很多地方标记。我只想要一个最后点击地点的地标。如何解决这个问题..?提前致谢。

您可以保留对标记的引用并继续移动它:

var marker;

function placeMarker(location) {
  if (!marker) {
    marker = new google.maps.Marker({
      position: location,
      map: map,
    });
  } else {
    marker.setPosition(location);
  }
  document.getElementById("latt").innerHTML = location.lat();
  document.getElementById("long").innerHTML = location.lng();
}

编辑:latitude 没有双 t 所以 id "lat" 更有意义。我可以向你保证,如果你拼错了,你的同事会因为不得不记住你拼错了而生气 :)

在添加新标记之前删除您的标记。

var map;
var marker;

function initialize() {

    var myCenter = new google.maps.LatLng(13.001294, 77.661736);
    var mapProp = {
        center: myCenter,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    google.maps.event.addListener(map, 'click', function (event) {
        placeMarker(event.latLng);
    });
}

function placeMarker(location) {

    // Remove last marker
    marker.setMap(null);

    marker = new google.maps.Marker({
        position: location,
        map: map,
    });

    document.getElementById("latt").innerHTML = location.lat();
    document.getElementById("long").innerHTML = location.lng();
}

google.maps.event.addDomListener(window, 'load', initialize);