After running my function in the desired way, where I open the context menu and then click the button, I notice an interesting behavior. The first time I run it, I see my desired result. However, every subsequent time I run it, the success message is displayed multiple times based on how many times it has been executed. It seems to be adding one more success message each time.
For those curious, this issue pertains to a Leaflet Maps project.
Additionally, it's crucial for me to have the functions within the main map.on function in order to capture the coordinates of the click event.
map.on('contextmenu', function(e) {
document.getElementById('context-menu').style.display = 'block';
document.getElementById('context-menu').style.left = e.originalEvent.x + 'px';
document.getElementById('context-menu').style.top = e.originalEvent.y + 'px';
function copyCoordinates() {
var lat = e.latlng.lat;
var lng = e.latlng.lng;
var zoom = map.getZoom();
var params = 'lat=' + lat + '&lon=' + lng + '&zoom=' + zoom;
var newUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + params;
navigator.clipboard.writeText(newUrl);
toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
document.getElementById('context-menu').style.display = 'none';
}
document.getElementById('copyCoordinates').addEventListener('click', copyCoordinates);
function copyCoordinatesFormatted() {
var lat = Math.floor(e.latlng.lat);
var lng = Math.floor(e.latlng.lng);
var formatted = '"lat": ' + lat + ',\n "lng": ' + lng + ',';
navigator.clipboard.writeText(formatted);
toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
var flag = true;
document.getElementById('context-menu').style.display = 'none';
}
document.getElementById('copyMarker').addEventListener('click', copyCoordinatesFormatted);
});
I attempted to address this by incorporating flags, but unfortunately, that did not resolve the issue.