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

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...

Why is the lower sub-component positioned above the rest of the page?

I have set up a sandbox environment to demonstrate an issue that I am facing. The main problem is that when I click on "Option 1" in the main menu, a new component appears where a bottom sub-component (named BottomControls.js) is displayed at the top of t ...

What is the best way to incorporate an ASYNC function within a .map function to dynamically populate a table in a REACT application?

I am attempting to use the .map() method in REACT to call an async function and populate table data cells. The async function communicates with the backend of my application using data from the array being looped through. When called correctly, the functi ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...

SwipeJS experiencing technical difficulties

My Swipe.Js version : "^7.0.2" Today, I attempted to use Swipe.Js and encountered an issue with my import code. import { Swiper, SwiperSlide } from 'swiper/react'; as described on https://swiperjs.com/react#installation. However, when ...

Utilizing JavaScript and PHP to dynamically load HTML content on a webpage

Below is the code snippet I'm working with: <?php if ($x == 1){ ?> <b>Some html...</b> <?php } else if ($x==2){ ?> <b> Other html...</b> <?php } ?> Now, I want to create two links (a ...

Always ensure that an element remains at the bottom during the sorting process

Currently, I have a list of items with an integer attribute that aids in sorting the list. However, I am looking for a way to designate specific items to always appear at the bottom of the list regardless of the sorting criteria. Is there a singular valu ...

Passing objects to an AngularJS form using UIB TypeAhead without two-way binding

In my current situation, I am encountering an issue with a typeahead feature on a repeating form element that consists of 5 input fields. While everything functions correctly when selecting results and populating the input fields, the model does not get up ...

Learn how to retrieve data by clicking on the previous and next buttons in FullCalendar using Vue.js

Seeking guidance on retrieving calendar data from the database for my Vue frontend, I have incorporated the fullcalendar API. Successfully able to retrieve data for the current week, however facing challenges when attempting to fetch data for the previous ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

A guide to sorting JSON objects in Node.js

let data={ '0': { benchmark: null, hint: '', _id: '54fe44dadf0632654a000fbd', date: '2015-05-10T01:11:54.479Z' }, '1': { benchmark: null, hint: '', _id: ...

The issue with updating values in the jQuery UI datepicker persists

When using the jquery datepicker ui, you may notice that the value attributes of the associated html fields do not update immediately. For example: http://jsfiddle.net/4tXP4/ Check out this link for more details: http://jqueryui.com/demos/datepicker/al ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema. In the past, I have created middlewares for JWT validation without passing any parameters, and they wor ...

Node.js is throwing an error code 344, indicating that it is not possible to manipulate headers after they have already been

I'm still learning about Node and I've encountered this confusing error that I can't seem to figure out. I've searched for similar cases online, but none of them quite match mine. Any help would be greatly appreciated. From what I gathe ...

MongoDB issued an error notification stating: "The operation `disneys.insertOne()` has experienced a timeout after 10000 milliseconds."

I am currently in the process of developing a new API using MongoDB and Express, and I have come across the following issue: "Operation disneys.insertOne() buffering timed out after 10000ms." To test my API, I am using route.rest. However, I ...

Switching Image Values in JavaScript: A Quick Guide

After successfully using a JavaScript function to swap the src of two images, I encountered an issue. I also needed to switch two values associated with the images so that I could calculate them later. For example: img src="ble.jpg" id="F" value="" onclic ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...