How to access arguments in a Leaflet API event listener

I am utilizing the leaflet api in conjunction with L.geoJson. Below are snippets of the relevant code:

var indiaLayer = L.geoJson(india, {style: {weight: 2,
        opacity: 1,
        color: '#F7BE81',
        dashArray: '10',
        fillOpacity: 0.2}});

Next, I set up an event listener on indiaLayer like so:

indiaLayer.on('click', clicked);  

If I want to access the first argument, in this case, 'india,' inside the clicked function, what syntax should I use? After consulting the DOM tree, I came up with:

alert(this._layers.22.feature.id);

Unfortunately, it resulted in a syntax error. Can anyone provide assistance with resolving this issue? Thank you.

I have also included the full code below:

<html>
<head>

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="india.js" type="text/javascript"></script>

</head>

<body>
<div id = "map1" style="width: 1100px; height: 400px"> </div>
<div id = "zoom" style="width: 100px;  height: 100px"></div>
<div id = "select" style="width: 100px; height:100px"></div>

<script>

var area = L.map('map1', {center: [27.8800,78.0800], zoom: 4 });

L.tileLayer('http://a.tiles.mapbox.com/v3/raj333.map-gugr5h08/{z}/{x}/{y}.png').addTo(area);

function zoomDeal()
{
    var zoom=document.getElementById("zoom");
    zoom.innerHTML= area.getZoom();
}

area.on('zoomend',zoomDeal);

var indiaLayer= L.geoJson(india, {style: {weight: 2,
        opacity: 1,
        color: '#F7BE81',
        dashArray: '10',
        fillOpacity: 0.2}});

area.addLayer(indiaLayer);

function clicked(){
if (area.getZoom() == 4) {
    if (this.options.style.fillOpacity == 0.5)
    {
        this.setStyle({fillOpacity: 0.2});
        this.options.style.fillOpacity=0.2;
        var select = document.getElementById("select");
        select.innerHTML = "";
    }
    else
    {   
        this.setStyle({fillOpacity: 0.5});   
        this.options.style.fillOpacity=0.5;  
        var select = document.getElementById("select");
        alert(this._layers.22.feature.id);
    }
}
}

indiaLayer.on('click', clicked);                

</script>
</body>
</html>

Answer №1

Be cautious when using the specific leaflet given id in the click handler as it may change if loaded elsewhere.

The default click handler includes the event argument. To access the origin of the click, you can modify your clicked function definition to:

function clicked (e) {
  // do stuff etc.
}

You can then access the layer with e.target.

An even better approach would be to include an onEachFeature function in the layer definition, which reads out the JSON. Take a look at this example: http://leafletjs.com/examples/geojson.html

The onEachFeature (http://leafletjs.com/reference.html#geojson-oneachfeature) allows direct access to the feature being accessed so you can perform actions accordingly, for example:

L.geoJson(india, {
  onEachFeature: function (feature, layer) {
    layer.on('click', function (e) {
      alert(e.target.feature.id)
    })
  }
});

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

Mapping JSON to JSON

We are in need of a JSON mapping tool that can convert Type-A to Type-B (JSON to JSON string). While there are ESB tools available for XML to XML mapping like IBM ESB, we require a similar tool for JSON. Are there any options available as open source tool ...

Material UI autocomplete bug: a frustrating issue with suggestions

I'm currently developing a single-page application using React, and I have a shipment page where multiple products and their quantities need to be added. I've implemented some functions for this scenario, and while they are working correctly (sen ...

Creating a dynamic field using Apollo GraphQL

Hey there, I've encountered an issue and despite my efforts to search for a solution, I couldn't find one. The problem at hand is creating a dynamic field in my GraphQL Type where the value depends on other fields. Essentially, if any of the oth ...

The implementation of the Flatlist React-Native component is causing a failure in populating my array, resulting in a

My goal is to load data from the backend and display it on the screen: async function fetchData() { try { const response = await api.get("data"); const newData = response.data; console.log(newData); setData(newData); cons ...

Is there a way for me to verify that the input value matches an email format?

Here is an example that I'm struggling with: link This is the HTML code: <input type="text" name="email" class="email" placeholder="Your email address"> This is the JavaScript code: $(document).ready(function ($) { function validateEm ...

Selecting dates based on week number

Is there a method in asp.net or via javascript to capture the dates (Monday to Friday) when a user clicks on the week number displayed on the calendar and display them on a label? ...

Enhancing User Experience with Jquery Dialog and Implementing Stylish Text Presentation

My goal is to design a customer support dialogue that includes a title and two lines of text. The first line should display an error message, while the second line will feature a bold customer service number. To provide further clarity, I have created a vi ...

Tips for transferring and incorporating custom helper functions in JS/React

Task at Hand: Instead of constantly typing console, I want to import some shorthand. For example-- log('hi') should be the same as console.log('hi') Attempted Solution: This is what I have so far. I want to use shortcuts like l ...

Can someone please explain the purpose of document.reservation.submit();?

As I delve into the code of a previous developer, my focus is on creating a reservation form. After a thorough review, it seems that the only reference to "reservation" is in the name and ID of the form. The form's style includes: display:none ... ...

What is the reason behind requiring an additional click to hide an element on the screen?

Currently, I am attempting to use the jQuery .hide() method to conceal a specific element. The issue arises when the active radio button is chosen as the element fails to hide immediately. Strangely, after selecting the button, the element only hides once ...

Revamp your JSON array by utilizing the JOLT transformation to selectively filter objects based on their

I am currently working on a Nifi dataflow where I am attempting to filter and transform JSON using the JOLT processor. This is a relatively new concept for me. The JSON input I am working with is: [ { "id": "1cca9371-b0f2-4c4d-9028-cd ...

Facing difficulty in submitting form data with Reactjs

I am currently working on a project using Reactjs with nextjs. I am facing an issue where I am unable to receive any response or see anything in the console.log when trying to post form data. I have tried implementing the following code in index.js, but ...

Fancy Text CSS Animation

I'm in the process of developing a landing page for a client. Their logo is prominently centered with the company slogan displayed directly underneath. At present, the slogan elegantly fades into view upon loading the page. Recently, they expressed i ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Visualization of pie charts in Angular2 using Google library

Currently, I am in the process of building a web application using Angular2 that includes a Google pie chart. One of the components of the application is a Directive specifically designed for the pie chart. Below is the code snippet for the Directive: @D ...

What is the best way to deactivate a submit button while an AJAX request is underway, and then reactivate it once a successful AJAX response is

I am working with the following HTML code: <form action="view_rebate_master.php" method="post"> <div class="form-group"> <label for="company_name" class="col-lg-12">Manufacturer</label> <div class="col-lg-12"> ...

Why am I unable to make a selection in the dropdown menu?

Can anyone help me figure out why I am unable to select an option from the material ui library and display it in the state? Has anyone else encountered this issue? For a detailed code example, check here import React from "react"; import ReactDOM from " ...

Send JSON data to an API using Angular

I have a route with POST Method 'http://localhost:5000/cities' where I can send json data like [{ "id:" 1, "name": "LA", "country": "USA", "value": 10000 }] In Angular, there is a servi ...

Browsing through the elements of a JSON array in a loop

I am facing a scenario where I have a JSON string structured as follows: {"data":[{"report_header":{"c1":{"name":"COLUMN1","type":"java.lang.String"},"c2":{"name":"COLUMN2","type":"java.lang.String"}},"report_row":[{"c1":"2019","c2":"TEST123"},{"c1":"2019 ...

Struggling with incorporating elements into a dynamic CSS3 banner design?

Struggling to add up to 10 text items to the CSS3 animated banner. Having difficulty getting the items to display properly. I'm curious if there is a simpler way to achieve this with animations as shown in this example: http://jsfiddle.net/zp6B8/1/ & ...