How do you add marker to map using leaflet map.on('click', function) event handler

孤街浪徒 提交于 2019-11-27 03:54:36

问题


I'm trying to use an event handler to add a marker to the map. I can manage this with a callback function, but not when I separate the function from the event handler.

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

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

Separate function (http://jsfiddle.net/rhewitt/U6Gaa/6/):

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

回答1:


in your fiddle code, your function is in the wrong scope. try moving the function inside the map function instead of in it's own scope... i.e. instead of:

});

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

use

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



回答2:


The main problem is that the variable map that you use inside the function addMarker is not the variable in which you store the created map. There are several ways to solve this problem but the easiest can be to assign the created map to the variable map declared in the first line. Here is the code:

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);
}



回答3:


var marker = L.marker([35.737448286487595, 51.39876293182373]).addTo(map);
var popup = marker.bindPopup('<b>Hello world!</b><br />I am a popup.');


来源:https://stackoverflow.com/questions/18388288/how-do-you-add-marker-to-map-using-leaflet-map-onclick-function-event-handl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!