I have a problem with a marker in leaflet. My code is this:
var updateMarker = function(lat, lng) {
if($('.leaflet-marker-icon').length)
marker.setLatLng([lat, lng]);
else
var marker = L.marker([lat, lng]).addTo(map);
return false;
};
var updateMarkerByInputs = function() {
return updateMarker( $('#latInput').val() , $('#lngInput').val());
}
$('#latInput').on('input', updateMarkerByInputs);
$('#lngInput').on('input', updateMarkerByInputs);
map.on('click', function(e) {
$('#latInput').val(e.latlng.lat);
$('#lngInput').val(e.latlng.lng);
updateMarker(e.latlng.lat, e.latlng.lng);
});
As you can see, on the first click will be add a marker and in the next clicks it should be updated. But I get this error at the second click:
TypeError: i is undefined
..."_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:funct...
leaflet.js (line 6, col 603)
What do I wrong?
I have a problem with a marker in leaflet. My code is this:
var updateMarker = function(lat, lng) {
if($('.leaflet-marker-icon').length)
marker.setLatLng([lat, lng]);
else
var marker = L.marker([lat, lng]).addTo(map);
return false;
};
var updateMarkerByInputs = function() {
return updateMarker( $('#latInput').val() , $('#lngInput').val());
}
$('#latInput').on('input', updateMarkerByInputs);
$('#lngInput').on('input', updateMarkerByInputs);
map.on('click', function(e) {
$('#latInput').val(e.latlng.lat);
$('#lngInput').val(e.latlng.lng);
updateMarker(e.latlng.lat, e.latlng.lng);
});
As you can see, on the first click will be add a marker and in the next clicks it should be updated. But I get this error at the second click:
TypeError: i is undefined
..."_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:funct...
leaflet.js (line 6, col 603)
What do I wrong?
Share Improve this question asked Sep 6, 2015 at 9:26 fibifibi 1491 gold badge7 silver badges13 bronze badges1 Answer
Reset to default 5You are defining your marker
variable locally in the updateMarker
function, so the reference is lost as soon as the function returns.
Define it outside the function:
var marker;
var updateMarker = function(lat, lng) {
if($('.leaflet-marker-icon').length)
marker.setLatLng([lat, lng]);
else
marker = L.marker([lat, lng]).addTo(map);
return false;
};
This way you don't need to check the DOM with jQuery to find out if your marker is defined, you can check directly the marker variable:
var marker;
var updateMarker = function(lat, lng) {
if (marker) {
marker.setLatLng([lat, lng]);
} else {
marker = L.marker([lat, lng]).addTo(map);
}
return false;
};
(to improve readability I would suggest to always use brackets in your if
statements.)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745063984a4609141.html
评论列表(0条)