Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked.

This is the current code snippet I have:

 for(var i = 0; i < this.markers.length; i++) //attaches listener to all markers
 {
      google.maps.event.addListener(this.markers[i], "click", () =>
      {
            //need a way to identify the clicked marker
      }); 
 }

I've experimented with passing arguments to the arrow function without success. Are there any suggestions or alternatives? The usage of an arrow function is not mandatory as long as the function can provide the index of the correct marker.

Answer №1

Please review the official documentation.

Check out this functional demonstration:

function startMap() {

  var mapOptions = {
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(1, 1)
  };

  var locations = [
    [new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
    [new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
    [new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
    [new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
    [new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
    [new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
  ];

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var infowindow = new google.maps.InfoWindow();

  for (var idx = 0; idx < locations.length; idx++) {

    var marker = new google.maps.Marker({
      position: locations[idx][0],
      map: map,
      title: locations[idx][1]
    });

    google.maps.event.addListener(marker, 'click', (function(marker, idx) {

      return function() {
        infowindow.setContent(locations[idx][2]);
        infowindow.open(map, marker);
      }

    })(marker, idx));
  }
}

startMap();
#map-canvas {
  height: 200px;
}
<div id="map-canvas"></div>

<script src="https://maps.googleapis.com/maps/api/js"></script>

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

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

Encountering a parse error when making an AJAX call using structural functions

I'm in the process of developing an API and here is my PHP function. function retrieve_schools($cn){ $schools_query = "SELECT * FROM schools"; $school_result = mysqli_query($cn, $schools_query); $response_array['form_data'][&apo ...

What is the mechanism behind angular2's spa routing functioning seamlessly without the need for the hash character in the url?

During my experience with the Angular2 "Tour of Heroes" tutorial, I made an interesting observation about how their single page application router functions without a trailing hash symbol (#) in the URL. This differs from the Kendo SPA router, which typica ...

Obtain specific fields from a multidimensional array object using lodash

My dilemma involves working with an object that has the following structure: var data = [ { "inputDate":"2017-11-25T00:00:00.000Z", "billingCycle":6, "total":1 },{ "inputDate":"2017-11-28T00:00:00.000Z", "bi ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms. Below is my current code: my_code.js: var my_data = { name: "fred", numbe ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

What design pattern serves as the foundation for Angularjs? Is mastering just one design pattern sufficient?

Although I have been teaching myself Angular and can understand how to code in it, I realize that simply learning the concepts of AngularJS and coding or tweaking things to solve problems is not enough. Moving forward, my goal is to write effective and sta ...

Excessive notification events are currently causing a blockage in the Angular app

Currently, I am utilizing Angular 7 in combination with SignalR on the backend for push notifications. At certain times, an overwhelming amount of notifications flood in, causing my application to become completely unresponsive. The SignalR service compon ...

Change numbers into a comma-separated style containing two decimal points using javascript

I have been working on a JavaScript function to convert numbers into a comma-separated format with two decimal places: Here is my current code snippet: Number(parseFloat(n).toFixed(2)).toLocaleString('en'); The issue with this code is that it ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

Oops! An uncaught exception error occurred because the primordials were not defined

I used npm to install the package called aws-s3-zipper, but now I am encountering an error. This is the code snippet causing the issue: AWS = require("aws-sdk"); var S3Zipper = require("aws-s3-zipper"); function zipFolderOnS3() { var zipper = new S3 ...

Having trouble using jQuery's .off() method to remove an event handler?

I'm facing an issue with my jQuery code where the .off('click') method doesn't seem to be working. I've tried removing the event binding from '.reveal-menu', but it's not working as expected. The initial animation wo ...

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

What is the approach for utilizing Vue List Rendering with v-if to verify the presence of items within an array?

My current implementation utilizes v-if to conditionally display a list of cafes. However, I am interested in filtering the list based on whether a specific drink item is found in an array. For instance, I have a collection of cafes and I only want to dis ...

I am encountering an issue where my ejs file is not rendering properly even after moving my static files to the public folder and including the line of code app.use(express.static("public")). Can anyone help

After relocating the index.html and css files to the public folder and adding app.use(express.static("public)) in app.js, everything was working fine and the list.ejs was rendering correctly. However, there seems to be an issue now. const express = re ...

Guide to logging in using REST/API with a Next.js application

Issue: I am facing a challenge integrating with an existing repository that was created using Next.js. The task at hand is to enable users to sign in to the application through a specific endpoint or URL. To achieve this, I have been attempting to utilize ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

Background image of HTML Iframe element does not display - Inline style block

https://i.stack.imgur.com/JW26M.png After setting the iframe's innerHTML using this line of code: iframedoc.body.innerHTML = tinyMCE.activeEditor.getContent(); The styles for the elements within the iframe are contained in an inline style block. Ho ...