2013-08-22 16 views
5

我想使用事件處理程序向地圖添加標記。我可以用一個回調函數來管理這個,但是當我將這個函數和事件處理函數分開時,不能這樣做。如何使用傳單map.on('點擊',函數)事件處理程序添加標記地圖

回調(http://fiddle.jshell.net/rhewitt/U6Gaa/7/):

map.on('click', function(e){ 
    var marker = new L.marker(e.latlng).addTo(map); 
}); 

單獨的函數(http://jsfiddle.net/rhewitt/U6Gaa/6/):

function newMarker(e){ 
    var marker = new L.marker(e.latlng).addTo(map); 
} 
+1

我認爲http://stackoverflow.com/questions/9912145/leaflet-how-to-find-existing-markers-and-delete-markers/24342585#24342585將幫助你添加以及刪除標記。 –

回答

12
在提琴代碼

,你的功能是在錯誤的範圍。嘗試在它自己的範圍內移動地圖功能裏面的函數,而不是...即代替:

}); 

function addMarker(e){ 
// Add marker to map at click location; add popup window 
var newMarker = new L.marker(e.latlng).addTo(map); 
} 

使用

function addMarker(e){ 
// Add marker to map at click location; add popup window 
var newMarker = new L.marker(e.latlng).addTo(map); 
} 
}); 
6

主要的問題是,你在函數內部使用的變量mapaddMarker不是您存儲創建的地圖的變量。有幾種方法可以解決此問題,但最簡單的方法是將創建的地圖分配給第一行中聲明的變量map。下面是代碼:

var map, newMarker, markerLocation; 
$(function(){ 
    // Initialize the map 
    // This variable map is inside the scope of the jQuery function. 
    // var map = L.map('map').setView([38.487, -75.641], 8); 

    // Now map reference the global map declared in the first line 
    map = L.map('map').setView([38.487, -75.641], 8); 

    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
     attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>', 
     maxZoom: 18 
    }).addTo(map); 
    newMarkerGroup = new L.LayerGroup(); 
    map.on('click', addMarker); 
}); 

function addMarker(e){ 
    // Add marker to map at click location; add popup window 
    var newMarker = new L.marker(e.latlng).addTo(map); 
} 
相關問題