How to Trigger Events When Clicking on Multiple Markers in Google Maps

Having an issue with my marker loop where all markers respond with the same value when clicked.

Below is my code snippet:

  for(a=0; a < prod.length; a++){      
  // adding marker to map  
  var myLatlng = new google.maps.LatLng(prod[a]['lat'],prod[a]['lon']);
  var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title: prod[a]['name']+" \n"+prod[a]['description'],
  icon: image
  });        
  google.maps.event.addListener(marker, "click", function() {
    show_details(a);
  });      
}

The problem lies in the 'show_details' function where 'a' always has the same value.

Despite checking other solutions, I couldn't find a fix for this issue.

Answer №1

Common issue seen in asynchronous programming and scripting. When the click event is triggered, the variable a passes along with it, however, the value of a is captured after the completion of the loop. To tackle this problem, it's recommended to create a nested function scope and store the value of a in a variable that exists only within that scope. The solution involves:

(function(z){
    google.maps.event.addListener(marker, "click", function() {
       show_details(z);
    });    
})(a);

It's worth noting that the variable

a<code> also persists outside the callback function. Therefore, any modifications made to the value of <code>a<code> (or within the <code>for
loop) will be reflected when the event handler is activated.

For further assistance, you can refer to: .

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

Troubleshoot: Why is fs.createReadStream in node.js only reading the last line of

Hello, I am currently facing some frustrating issues while trying to stream the contents of my CSV file. Below is the code snippet I am using, and my struggles are hidden in the comments. var fileReadStream = fs.createReadStream(inFile); // I&a ...

What are some best practices for preventing unforeseen rendering issues when utilizing React Context?

I am encountering an issue with my functional components under the provider. In the scenario where I increase counter1 in SubApp1, SubApp2 also re-renders unnecessarily. Similarly, when I increase counter2 in SubApp2, SubApp1 also gets rendered even thou ...

Exploring the relationship between variables and closure scope in the context of anonymous

Each time the anonymous function is invoked with a parameter, it encapsulates everything within itself. If another call to the subscribed function occurs before the first anonymous function's callback from the database or ajax call, it will not affect ...

The initial dispatch of a React hook triggers subsequent dispatches to fire multiple times

Whenever I include more than one dispatch in useEffect(), it causes all subsequent actions to be triggered twice. Please see the example below. Below is the complete code. Feel free to remove comments in any order you prefer. PS: I am not sure how to mak ...

Outputting an object using console.log in Node.js

When I print the error object in nodejs, the result of console.log(err) appears as follows: { [error: column "pkvalue" does not exist] name: 'error', length: 96, severity: 'ERROR'} I'm curious about the information enclosed ...

Samsung browser encounters an international error

After developing my web application using Angular2 Rc1, I noticed that it functions perfectly on Safari, Firefox, and Chrome browsers. However, when trying to access the application on my Galaxy S6 using the default browser, an error pops up: https://i.s ...

What is the best way to incorporate multiple input boxes into a single alertbox for repeated use?

I attempted to use the same alertbox for 3 different input elements by converting it into a class and using getElementsByClassName, but unfortunately, it did not work as expected. Here is what I tried: <input type="text" class="form-control date notif" ...

A guide on utilizing should.js to verify object equality when dealing with a property value that is NaN

It appears that there may be a bug in should.js related to the special value NaN, which is not equal to itself. ({ a: 1, c: 3, b: 2, d: NaN }).should.eql({ a: 1, c: 3, b: 2, d: NaN }); Despite the expectation that this tes ...

Having trouble with implementing static properties in a JavaScript Class within Vue

In my Vue2 App, I encountered an issue when trying to import a class with a static property from a separate file. export class TestUnit { static testVar = "test"; } Upon attempting to import the class using: import { TestUnit } from ".. ...

Exciting Funnel Design with Highcharts

As someone new to the world of Highcharts library, I am eager to create a horizontal funnel. I noticed there is an example of a vertical funnel on http://www.highcharts.com/demo/funnel but I couldn't find any options to make it appear horizontal. I&ap ...

Extracting values from URL query parameters in Vue.js

When dealing with Vue.js callback URLs, I encounter situations where I need to extract a parameter value from the URL. For instance, consider this return URL: http://localhost:8080/#/sucesspage?encryteddata=abdeshfkkilkalidfel&9a I attempted to retrie ...

"IOS exclusive: Encounter INVALID_STATE_ERROR on IOS devices only, not on Android, OSX, or Windows platforms

While developing an HTML5 web page with audio functionality using JavaScript, I encountered an issue. Initially, the basic version of my webpage successfully loaded and played audio files in different formats (e.g., ogg vs mp3) across various OS/browser co ...

Rendering Based on Conditions in React Native

I'm a beginner in the world of React Native and coding and I'm looking to display text based on certain variables (as shown below). If isPlayer === true && base.length === 1, then display x Else if isPlayer === true && base.leng ...

Struggling with integrating API response formatting in React and updating state with the data

This is the content found in the file 'Search.js' import React, { Component } from 'react'; import * as BooksAPI from './BooksAPI' class Search extends Component{ constructor(props){ super(props); this.state={ ...

Experiencing excessively rapid zooming in JavaFX Leaflet on WebView

Incorporated a Leaflet map into my JavaFX project, but encountered a zoom speed issue. When I zoom in by one step, it zooms all the way to the size of Iceland: https://i.sstatic.net/BkReA.jpg The expected behavior is for the map to zoom in just slightly: ...

Passing PHP Variables to Multiple Pages

I seem to be facing a bit of a challenge. I am successfully sending the variable c_prot to the page parsing.php. However, I also need to send this same variable to the page chart.php, but it doesn't quite work as expected. If you have encountered a si ...

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

Tips for choosing the remaining items in a multiple selection process

In my HTML form, I have a multi-select field that contains categories and the corresponding items within each category. My goal is to allow users to select individual courses or select an entire category (identified by values starting with "cat_") in orde ...

What is the method for accessing HTML tag data within a script?

Looking for a way to extract a specific substring from a given string: var str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`; Is there a method to extract the following substring? 'Enter a valid email ...

Executing CORS request using Node.js/Express and AngularJS

I've come across multiple responses on Stack Overflow claiming that setting response headers will resolve CORS requests. However, none of the solutions have worked for me. Here is the code I have implemented: //Server.js Code var express = require(&a ...