Google map api v3 - 在进行地理编码时删除旧标记

ron*_*dev 4 javascript google-maps-api-3

我是新的Javascript和谷歌地图api我一直按照这个链接删除标记,但有些我不能使它工作.

基本上我想在用户输入地址并单击按钮时使用按钮生成标记.当用户输入新地址并再次单击该按钮时,旧标记将被删除,新标记将固定在新地址上.标记也可拖动.

这是我的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);
                                }
                    });
            }
Run Code Online (Sandbox Code Playgroud)

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

未捕获的TypeError:无法调用未定义的方法'setMap'

Bry*_*ver 14

您需要引用marker对象才能在以后访问它.如果要将地图限制为一次marker显示,则可以更新markers 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
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

}
...
Run Code Online (Sandbox Code Playgroud)

这是一个概念的小提琴. 您可以单击地图,标记将移动到所需位置.