i have installed a leaflet map and have tried several times to add a popup to the map that supports HTML text and contains a button. The problem with the below version is that the button appears but when you try to add a function when the button is pressed it doesn't work.
var popup = L.popup({
offset: [0, -30]
})
map.on('click', (e) => {
const lng = e.latlng.lng,
lat = e.latlng.lat
$('#lng').val(lng)
$('#lat').val(lat)
$('#phi').val(CalcBeta(lat))
AddMarker(lat, lng)
popup
.setLatLng(e.latlng)
.setContent('<b>Your selected Location</b><br>Longitude: '+e.latlng.lng.toString()+'<br>Latitude: '+e.latlng.lat.toString()+'<br>Power supply: test<br>Water supply: test<br>Panel tilt angle: '+CalcBeta(lat)+'<br><br><center><button id="getres">More details</button>')
.openOn(map);
})
The other version I found in a forum is the one below where the button works but you can't use HTML text inside the popup.
//var choicePopUp = L.popup();
//var container = L.DomUtil.create('div');
//var txtcontent = document.createTextNode('');
//container.append(txtcontent);
//Btn = this.createButton('Go to this location', container);
//choicePopUp
// .setLatLng(e.latlng)
// .setContent(container)
// .openOn(this.map);
//L.DomEvent.on(Btn, 'click', () => {
// alert("tata");
//});
Do you have an idea how to get the 1st or the 2nd version or maybe a completely different approach?
Thank you for your help.
If you want to bind a click to your button, you need to bind the click event in the same scope as you create the Popup
.
You can do this in this way :
map.on('click', (e) => {
const lng = e.latlng.lng;
const lat = e.latlng.lat;
$('#lng').val(lng);
$('#lat').val(lat);
$('#phi').val(CalcBeta(lat));
AddMarker(lat, lng);
popup.setLatLng(e.latlng)
.setContent('<b>Your selected Location</b><br>Longitude: '
+ e.latlng.lng.toString()
+ '<br>Latitude: '
+ e.latlng.lat.toString()
+ '<br>Power supply: test<br>Water supply: test<br>Panel tilt angle: '
+ CalcBeta(lat)
+ '<br><br><center><button id="getres">More details</button>')
.openOn(map);
// We bind the click event here in the same scope as we add the Popup
document.getElementById('getres').addEventListener('click', (e) => {
console.log('click !');
// Here you can do your stuff
});
})