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

Issues regarding ambient getters and setters

Recently, I encountered an issue with my open-source library called Firemodel. The library utilizes ES classes and getters/setters within those classes. Everything was working smoothly until my VueJS frontend code started flagging every instance of these g ...

If a generic string argument is not specified as a string literal, it will not be narrowed unless it is the first argument

When the following code is executed, it works as intended and we can see that the arg variable is a string literal: const foo = <T extends string = string>(arg: T) => {}; foo('my string'); // const foo: <"my string">(arg ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...

The useParams() function encounters difficulty in converting data to number typescript

Whenever I try to convert the heroId type from string to number in my code, I always encounter an error. Here is the code snippet: import useHero from '../../hooks/useHero'; import {useParams} from 'react-router-dom' function Herospag ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...

Utilize Firebase for Playwright to efficiently implement 'State Reuse' and 'Authentication Reuse'

In my testing environment, I want to eliminate the need for repeated login actions in each test run. My approach involves implementing 'Re-use state' and 'Re-use Authentication', but I've encountered a challenge with Firebase using ...

Potential Unresolved Promise Rejection (ID: 0): The object 'prevComponentInstance._currentElement' is undefined

Attempting to fetch JSON data in react native using axios.get(my_url_path), then updating the state with response.data under the key 'urldatabase'. When attempting to access this state key and read the data from the JSON, an error is encountered: ...

When the submit button is clicked, only the last form within the function will be submitted

I currently have a submit button that is meant for 3 different forms. When submitting, I use the following approach: restaurantCreateForm = function(){ document.getElementById("restaurant-features" ).submit(); document.getElementById("information_ ...

Reverting back to PDF using jQuery

I am currently utilizing jQuery to send JSON data back to the server, which in turn generates a PDF report. However, I am facing an issue where the PDF is not downloading despite specifying the necessary response header and including JavaScript as shown ...

What is the best way to load a database URL asynchronously and establish a database connection prior to the initialization of an Express

My express.js app is set up to run on AWS lambda, with the database URL stored and encrypted in Amazon KMS. To access the URL, decryption using the AWS KMS service is required. // imports import mongoose from 'mongoose'; import serverless from & ...

Performing real-time arithmetic calculations on dynamic text input fields using AngularJS

In the process of creating a dynamic form, the number of textboxes is determined by the situation at hand. Each textbox is assigned an arithmetic formula, which is obtained from a database table. The structure of my form will be as follows: <div ng-ap ...

Using jQuery to create dynamic elements that fade out with timers

My website has a simple message system that displays messages in a floating div at the top of the page. Each message is supposed to fade out after a certain amount of time, but I want users to be able to pause the fading process by hovering over the messag ...

I currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'you ...

Ways to fetch a JSON object using JavaScript

Currently, I am in the process of creating an HTML5 mobile application and utilizing jQuery to fetch a JSON file from this URL: . Here is the code snippet I used: var url='http://cin.ufpe.br/~rvcam/favours.json'; $.getJSON(url, function(data, s ...

"Here's a neat trick for assigning the value of a div to a text box without any identifiers like id or

I needed a way to transfer the value of a .item div into an empty textbox without any specific identifier. Then, when the input loses focus, the value should be sent back to the original .item div. $(document).on("click", ".item", function() { $(this) ...

Examining the dimensions of a div element in AngularJS

As I delve deeper into understanding AngularJS and tackling the intricacies of how $watch operates, a specific scenario has caught my attention. I want to monitor and track changes in the dimensions of the div element with an ID of "area". My intention is ...