移除之前的标记(Google 地图)

Remove previous marker (Google Maps)

我正在使用 Shreerang Patwardhan 的代码进行 Javascript 地理编码。但是,我在输入新地址时遇到了删除先前标记的困难。我用谷歌搜索并进行了试验,但我就是得不到我想要的结果。当放置新标记时,我想要以前的标记 removed/hidden。

HTML:

<html>
  <head>
    <title>Google Maps API v3 Example : Geocoding Simple</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    </script>
  </head>
  <body onload="initialize()">
    <div align="center" style="height: 30px; width: 430px">
      <input id="address" type="textbox">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map" style="height:200px; width: 430px"></div>
  </body>
</html>

Javascript:

var geocoder;
var map;
function initialize()
{
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById("map"),
    {
        zoom: 8,
        center: new google.maps.LatLng(22.7964,79.5410),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}

function codeAddress()
{
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker(
            {
                map: map,
                position: results[0].geometry.location
            });
        }
        else
        {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

我使用的代码与 this JS Fiddle:

中的代码相同

你需要做一个marker.setMap(null);标记是对之前标记的引用

 if(marker)
     marker.setMap(null)

https://jsfiddle.net/F4Sd2/637/ 是有效的 fiddle