2015-11-08 65 views
1

我的代碼有問題。我在地圖上顯示標記,但不會更改標記位置,而只會在我的地圖上添加新標記。如何刪除小冊子上的當前標記並再次添加新的標記?

我有我的問題的打印屏幕。

enter image description here

如何刪除以前的標誌?

這裏是我的代碼:

var latB = 0; 
var lonB = 0; 
var mark = 0; 
var marker = null; 
function showOnMap(a){ 
    convert_location(a); 
    marker = L.marker([latB, lonB]).bindPopup(a); 
    map.removeLayer(marker) 
    map.addLayer(marker); 
} 

function convert_location(a){ 
    var toData = (function(){ 
      var toData = null; 
       $.ajax({ 
        'async': false, 
        'global': false, 
        'url': 'http://nominatim.openstreetmap.org/search?format=json&limit=5&q='+a, 
        'dataType': 'json', 
        'success': function(data){ 
         toData = data; 
        } 
       }); 
      return toData; 
    })(); 

    $.each(toData, function(key, val){ 
     latB = val.lat; 
     lonB = val.lon; 
    }); 

} 
+0

歡迎來到SO!如果您可以在[jsfiddle](http://jsfiddle.net/)上重現您的問題,那麼您可以使人們的理解更加容易,並且可以讓他們直接向您展示如何使代碼變得可行。 – ghybs

回答

0

你擦除標記設置到一個新的引用後,所以基本上要刪除不存在的新的標記,然後將它添加到地圖中。 標記在重新分配之前應從地圖中刪除。

function showOnMap(a){ 
    convert_location(a); 
    if (marker != null) map.removeLayer(marker); 
    marker = L.marker([latB, lonB]).bindPopup(a); 
    map.addLayer(marker); 
} 
相關問題