Reputation: 107
I want to create a button within the leaflet popup, which when clicked it will zoom in to the point's location. I have defined the button and its event within the pointToLayer()
function. When clicked the button does not respond, and no error is reported when I check the developer tools in the web browser. What is not right?
Code
var controllayer = L.geoJSON(JSON.parse(response), {pointToLayer: function(feature, latlng){
//popup information
var str = "<h7>" + "<b>Old Control Name: </b>" + feature.properties.controlname1 + "</h7><br>";
str += "<h7>" + "<b>New Control Name: </b>" + feature.properties.controlname2 + "</h7><hr>";
str += "<h7>" + "<b>Northing: </b>" + feature.properties.northing + "</h7><br>";
str += "<h7>" + "<b>Easting: </b>" + feature.properties.easting + "</h7><hr>";
str += "<button id = 'zoomto' class = 'btn btn-primary center-block'>Zoom In</button>";
//event for the defined button
$("#zoomto").click(function(){
mymap.setView([latlng.lat, latlng.lng], 17);
});
return L.marker(latlng).bindPopup(str);
}}).addTo(mymap);
I defined the "controllayer" inside a success function in ajax, in order to load the point data from the server.
The entire ajax code section looks like this,
$.ajax({
url:'load_control.php',
success:function(response){
var controllayer = L.geoJSON(JSON.parse(response), {pointToLayer: function(feature, latlng){
//popup information
var str = "<h7>" + "<b>Old Control Name: </b>" + feature.properties.controlname1 + "</h7><br>";
str += "<h7>" + "<b>New Control Name: </b>" + feature.properties.controlname2 + "</h7><hr>";
str += "<h7>" + "<b>Northing: </b>" + feature.properties.northing + "</h7><br>";
str += "<h7>" + "<b>Easting: </b>" + feature.properties.easting + "</h7><hr>";
str += "<button id = 'zoomto' class = 'btn btn-primary center-block'>Zoom In</button>";
//event for the defined button
$("#zoomto").click(function(){
mymap.setView([latlng.lat, latlng.lng], 17);
});
return L.marker(latlng).bindPopup(str);
}}).addTo(mymap);
mymap.fitBounds(controllayer.getBounds());
}
});
Upvotes: 1
Views: 659
Reputation: 1817
The problem is simply that at the time of binding the click event, there is no element on the page with an id of "zoomto".
If you bind to the document and filter events with the "#zoomto" query selector you will get the desired behaviour.
//event for the defined button
$(document).on("click","#zoomto",function() {
mymap.setView([latlng.lat, latlng.lng], 17);
});
As pointed out by ghybs the concept of allowing an event to bubble up the DOM tree and handle it at a parent DOM node that we choose to delegate is called Event Delegation.
This concept is not specific to your chosen library (jQuery); but here is a jQuery flavoured Event Delegation tutorial: https://learn.jquery.com/events/event-delegation/
Upvotes: 2