Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map.

My goal is to have the popup display 2 buttons:

  • Start from Here
  • Go to this Location

The desired outcome looks like this sketch:

 ________________________________________________
|You clicked the map at LatLng(XXXXX,XXXXX)      |
|  ---------------    -------------------        |
| |Start from here|  |Go to this location|       |
|  ---------------    -------------------        |
|___________________  ___________________________|
                   \/

However, my current popup displays: "You clicked the map at LatLng(XXXXX,XXXX) [object HTMLButtonElement]."

I am attempting to create the buttons using L.domUtil.

defineYourWaypointOnClick(e: any) {

var choicePopUp = L.popup();
var container = L.DomUtil.create('div'),
  startBtn = this.createButton('Start from this location', container),
  destBtn = this.createButton('Go to this location', container);

choicePopUp
  .setLatLng(e.latlng)
  .setContent('You clicked the map at ' + e.latlng.toString() + '<br>' + startBtn)
  .openOn(this.map);

L.DomEvent.on(startBtn, 'click', () => {
  alert("toto");
});

L.DomEvent.on(destBtn, 'click', () => {
  alert("tata");
});
}

createButton(label: string, container: any) {
    var btn = L.DomUtil.create('button', '', container);
    btn.setAttribute('type', 'button');
    btn.innerHTML = label;
    return btn;
}

I trigger my method from here:

this.map.on('click', (e: any) => {
  this.defineYourWaypointOnClick(e);
});

Your assistance with this matter would be greatly appreciated. Thank you :)

Answer №1

It is recommended to utilize innerHTML for adding buttons to your leaflet map as shown in the code snippet below:

defineYourWaypointOnClick(e: any) {

var choicePopUp = L.popup();
var container = L.DomUtil.create('div');
//////////////////////////////////////////////////////////////////////////////////////////////
///////////updated section
startBtn = this.createButton('Start from this location', container),
destBtn = this.createButton('Go to this location', container);
div.innerHTML = ''+startBtn+ '&nbsp;&nbsp;&nbsp;&nbsp;' + destBtn ; 
//////////////////////////////////////////////////////////////////////////////////////////////

choicePopUp
  .setLatLng(e.latlng)
  .setContent('You clicked the map at ' + e.latlng.toString() + '<br>' + startBtn)
  .openOn(this.map);

L.DomEvent.on(startBtn, 'click', () => {
  alert("toto");
});

L.DomEvent.on(destBtn, 'click', () => {
  alert("tata");
});
}

createButton(label: string, container: any) {
var btn = L.DomUtil.create('button', '', container);
btn.setAttribute('type', 'button');
btn.innerHTML = label;
return btn;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

Can I send JavaScript variables to a different .PHP file by using Ajax?

I need to transfer javascript variables from one file where calculations are performed to another file containing a mySQL query. The second file is loaded using a .load() function without refreshing or redirecting to it. Is it possible to achieve this wit ...

Ensure consistency in CSS3 background color transitions

There are multiple elements on the webpage with background transitions that change from one color to another: @-moz-keyframes backgroundTransition /* Firefox */ { 0% {background-color:#ff7b7b;} 33% {background-color:#7fceff;} 66% {backgr ...

What is the best way to dynamically swap out an image within an element?

Is there a way to dynamically replace this image without deleting the HTML SVG element and re-rendering it? xlink:href="http://missosology.info/forum/download/file.php?avatar=11666_1307312313.jpg" CODE: https://jsfiddle.net/bfv17f0e/ <svg class="clip ...

How can one check in JavaScript if a specific URL was targeted with a XMLHttpRequest?

While I am familiar with monitoring network traffic in the browser's development tools and having XMLHttpRequests shown in the console, I am curious if there is a specific window property that showcases all network activity at once? ...

How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

Re-establishing the socket channel connection in a React application after a disconnection

There are several solutions to this issue, but none of them seem to be effective for me. The existing solutions are either outdated or do not meet my needs. I am facing a problem where I have a large amount of data being transferred from the server to the ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Encountering an issue with Jest when using jest.spyOn() and mockReturnValueOnce causing an error

jest --passWithNoTests --silent --noStackTrace --runInBand --watch -c jest-unit-config.js Project repository An error occurred at jest.spyOn(bcrypt, 'hash').mockRejectedValue(new Error('Async error message')) Error TS2345: The argum ...

Unable to deploy the Firebase function to Firebase functions platform

I've been watching Doug's video on YouTube for guidance on changing a message with functions in JavaScript. To resolve the error message 'types can only be applied to ts files,' I installed the Flow language script. Thankfully, that err ...

Adding HTML and scripts to a page using PHP and JS

Currently, I am utilizing an ajax call to append a MVC partial view containing style sheets and script files to my php page. Unfortunately, it seems that the <script> tags are not being appended. After checking my HTTP request on the network, I can ...

Optimal method for file uploading with Node.js

How can I effectively manage file uploads in node js? I would like users to be able to upload profile images with the following specifications: -Validated size of at least 200 * 200 -Accepted file formats are png, jpg, jpeg, or gif -Additional functi ...

Having trouble submitting data to a NextJS API route?

I am currently working on a simple form within a NextJS page, where the data is being stored in state: const [bookingInfo, setBookingInfo] = useState({ name: "", email: "", phone: "", }); const handleChange = (e ...

Troubleshooting the pushstate back function in HTML5 and jQuery

In my code, I have implemented an ajax call to load content dynamically. I am now looking to add a deeplinking effect, and after researching, I discovered that only raw coding can achieve this. Here is what I have implemented so far: jQuery("#sw_layered_c ...

ng-repeat not functioning properly when using track by, filter, and orderBy

I have come across this code snippet. http://jsfiddle.net/0tgL7u6e/ Scripting in JavaScript var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.nameFilter = ''; $scope.contacts = [ {name: 'G ...

A guide on displaying a text file from a URL in a reactjs application

When utilizing the code provided below, I have successfully managed to display the content of a local text file on a webpage. However, when attempting to render a text file from a URL, the state becomes null resulting in an empty display. In order to ren ...

When running the command ng build --prod, it seems that the module for class X cannot be determined. To resolve this issue, make sure to include

I'm encountering an issue while trying to develop my Angular 5 application. The error message reads: Cannot determine the module for class ThreadListTabsComponent in /home/brightwater/Differ/src/app/thread-lists/thread-lists.component.ts! Add T ...

The email protected function is failing to display components and is not generating any error logs

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05776064667128776a7071607728616a6845332b31">[email protected]</a> seems to be having trouble rendering components. I've been away from React for a bit and now I ...

Difficulties encountered when trying to load a URL or API that contains an array in javascript/p5js

I've run into a coding issue that I'm trying to troubleshoot in p5js. My goal is to retrieve data from a URL/API. The line `kursMin[1]...` gives the correct stock value, but the line `kursMin[i]` returns `[object Object]2021-03-124. close` Bo ...

VueJS Array Index causing unexpected output

I have been developing a unique poetry application that pulls in poetry using an API call. To fetch the data, I am utilizing the axios library and using v-for to render the data. The index from v-for is used to load the image for each respective poem. My ...