【问题标题】:Google map api v3 - remove old marker when doing geocodingGoogle map api v3 - 进行地理编码时删除旧标记
【发布时间】:2013-05-15 17:21:06
【问题描述】:

我是 Javascript 和谷歌地图 api 的新手,我一直在关注这个 link 来删除标记,但有些我无法让它工作。

基本上我想在用户输入地址并单击按钮时使用按钮生成标记。当用户输入新地址并再次单击按钮时,旧标记将被移除,新地址上的新标记销。标记也是可拖动的。

这是我的js代码:

$('#geocode').live('click',function() {
        codeAddress();
        return false;
});    

function codeAddress() {
                    var address = document.getElementById('location').value;
                    geocoder.geocode( { 'address': address}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {

                                map.setCenter(results[0].geometry.location);
                                if (marker) marker.setMap(null);
                                if (marker) delete marker;
                                var marker = new google.maps.Marker({
                                     draggable:true,    
                                      map: map,
                                      position: results[0].geometry.location
                                  });

                                 var newlat = results[0].geometry.location.lat();
                                 var newlng = results[0].geometry.location.lng(); 
                                 document.getElementById('mwqsflatlng').value = (newlat+' , '+newlng);
                                  draggeablemarker(marker);
                                } else {
                                  alert('Geocode was not successful for the following reason: ' + status);
                                }
                    });
            }

更新 当我检查检查元素时,它给了我这个错误:

未捕获的类型错误:无法调用未定义的方法“setMap”

【问题讨论】:

    标签: javascript google-maps-api-3


    【解决方案1】:

    您需要引用您的marker 对象才能在以后访问它。如果您想将地图限制为一次显示一个 marker,您可以更新标记 Position 属性,而不是删除并重新创建它。

    这是一个可以更改标记位置或在地图上不存在标记时创建新标记的功能。 location 参数是一个 Google LatLng 对象,与 Geocoder 返回的对象 results[0].geometry.location 相同。

    注意marker 变量是在函数范围之外定义的。这使您可以在以后参考标记。

    var marker;
    
    function placeMarker(location) {
        if (marker) {
            //if marker already was created change positon
            marker.setPosition(location);
        } else {
            //create a marker
            marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable: true
            });
        }
    }
    

    因此,对于您的地理编码成功函数,您只需要将结果传递给此函数。

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           placeMarker(results[0].geometry.location);
    
    }
    ...
    

    Here is a fiddle of of the concept.您可以点击地图,标记将移动到所需位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      相关资源
      最近更新 更多