javascript - 删除以前的标记(谷歌地图)

标签 javascript google-maps marker

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

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

关于javascript - 删除以前的标记(谷歌地图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42020268/

相关文章:

android - 如何在 Android 的谷歌地图中绘制徒手多边形?

Android 标记点击功能

javascript - 大学类(class)注册脚本

javascript - 我如何推迟像 jquery Deferred 这样的 ES6 promise?

android - IntentService 和 Activity 生命周期

android - 在没有 Google API 的情况下在 Android 中使用 Google map

javascript - 如何使用 gmaps4rails 在 rails 中旋转标记?

svg - 如何重用不同维度的<defs>标签中定义的<marker>?

javascript - Charts.js : Moment is not defined (using chart. bundle .min.js)

javascript - google.maps.MapOptions + JSON : avoid eval()?