2013-05-15 56 views
3

我是新來的Javascript和谷歌地圖API,我一直在關注這個link刪除標記,但一些我不能使它工作。Google map api v3 - 在做地理編碼時刪除舊標記

基本上我想用一個按鈕來產生標記,當用戶輸入一個地址並點擊按鈕。當用戶輸入一個新地址並再次點擊該按鈕時,舊標記將被刪除,新標記將被插入新地址。標記也可拖動。

這裏是我的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); 
           } 
        }); 
      } 

更新 當我檢查檢查元素,它給了我這個錯誤:

Uncaught TypeError: Cannot call method 'setMap' of undefined

回答

11

你需要有一個參考到您的對象,以便以後能夠訪問它。如果您想將地圖限制爲一次顯示,則可以更新標記Position屬性而不是刪除並重新創建它。

這是一個函數,可以更改標記位置或創建一個新標記(如果地圖上不存在)。 location參數是一個Google LatLng對象,它與Geocoder results[0].geometry.location返回的對象相同。

通知的變量函數範圍之外限定。這可以讓你稍後參考標記。

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.您可以點擊地圖,標記將移動到所需位置。

+0

太棒了!它正在工作。非常感謝。 –