The Google Maps infowindow consistently displays the first infowindow for all other markers, regardless of which marker

I've come across similar questions about this issue, but none of the solutions I found have worked for me. Maybe I'm missing something important.

Any assistance would be greatly appreciated.

The challenge I'm facing involves a map with over 1000 markers being loaded. When a user hovers their mouse over a marker, I want an infowindow to display that shows information specific to that marker's location.

However, the problem I'm encountering is that the same infowindow pops up over every marker, regardless of which one I hover over.

Below is a screenshot showing the map with all the markers and a single infowindow. As mentioned, no matter which marker I hover on, that same infowindow appears.

Here is the code snippet (gm represents an instantiated google.maps object):

for (var i = 0; i < opts.LocationsData.length; i ++) {
    var datum = opts.LocationsData[i];
    var icon = new gm.MarkerImage(datum.map_pin_loc + datum.map_marker + '.svg',null, null, null, new google.maps.Size(31,51));
    var loc = new gm.LatLng(datum.latitude, datum.longitude);
    var zi = 500;
    if(i>9)
    {
        datum.map_pin_icon = datum.map_pin_loc + 'dot1.svg';
        icon = new gm.MarkerImage(datum.map_pin_icon,null, null, null, new google.maps.Size(8,8));
        zi=450;
    }

    var marker = new gm.Marker({
        position: loc,
        /** title: datum.title != '' ? datum.title : datum.description, **/
        icon: icon,
        zIndex: zi,
        map: map
    });
    marker.type = 'point';
    marker.post_id = datum.pin_id;
    marker.scrollAndAnimate = true;

    /** (these are used elsewhere in my code for marker management and other purposes) **/
    markers.push(marker);
    markersLatLngObjs.push(loc);

    var infowindow = new gm.InfoWindow({
        content: '<strong>' + (datum.title != '' ? datum.title : datum.description) + '</strong>'
    });
    gm.event.addListener(marker, 'mouseover', function() {
        infowindow.open(map,marker);
    });
}

Answer №1

The issue arises from the mouseover event handler being a closure that references variables unique to the calling function's context. To resolve this, it is recommended to move this section outside of the loop for better clarity.

One approach is to define a function like:

function displayInformation() {
    // accessed within marker context
    var data = info.LocationsData[this.pointIndex];
    var popup = new googleMap.Popup({
        content: '<strong>' + (data.name != '' ? data.name : data.text) + '</strong>'
    });
    popup.open(map, this);
}

Right before your loop, you can create the function and then assign a pointIndex property to each marker inside the loop:

marker.pointIndex = i;

Lastly, attach the handler using:

googleMap.event.addListener(marker, 'mouseover', displayInformation);

Update: Apologies for the oversight, there are other references to consider as well, leading to the same problem. You can potentially replace 'marker' with 'this' within the handler function. I have made adjustments to the code.

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

Guidelines for initiating a new function with JavaScript and AJAX

Is it possible to trigger another function once an ajax call has been completed? I am looking to implement a callback function following the successful registration of a user, however, my sign-up function seems to stop working when I attempt to do so: f ...

The reflow feature in Highcharts does not properly update the width of the container for High

https://i.sstatic.net/8Shix.gif I am currently working on adjusting the width of Highcharts dynamically to fit its parent container. To achieve this, I have set up a mechanism that listens to changes in the sidebar state and triggers a reflow function whe ...

Display data in Bootstrap table using JQuery and JSON

Can anyone help me figure out how to populate my bootstrap table (in Database.Master) with data (in DatabaseUI.aspx.cs)? I need to dynamically add rows to the table using JQuery. Do I need to convert my string to JSON first? I believe I may have to add an ...

The functionality of saving a file using the jsPDF method is not functioning properly

After dedicating four days to resolving a seemingly straightforward task that involved the jsPDF library, I found myself faced with a challenge. My goal was to save a file using this library, not just print it like I had successfully done before. This is ...

Is there a way to retrieve the values for North, East, South, and West separately?

let coordinates = [ { mapview_id: [ { west: 11.5, south: 55.75, east: 12, north: 56, }, ], }, ]; I'm encountering a constant issue with this data retrieval process. Every attempt to access the d ...

Is it possible to update a nested array using the onChange function in useState?

In my application, I am dealing with a simple state that consists of an array of objects. One of these objects contains another array of objects inside it. While I have successfully implemented an onChange handler to modify the basic state, I am encounteri ...

Tips for embedding HTML components within a div element through JavaScript

Can you help me transform this code into a div element using JavaScript? <div id=parentDiv> <div id="question1"> QuestionNo 1 <button onclick="setOption(1,1)">A</button> <button onclick="setOption(1, ...

Experiencing a challenge with $http.post in Angular js when using it with node

Despite my server functioning correctly and returning the desired result, I am facing an issue where my angularjs $http.post .then method is not being executed, neither is the .catch method. The node js controller below is responsible for validating if an ...

ReactJS: The Battle of CDN vs NPM - What's the Best Option?

As someone new to web development, I'm eager to create a polished website and turn it into a seamless single-page application with ReactJS. However, I find myself torn between utilizing CDN or NPM. Can you offer some guidance on this matter? ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

Starting an HTML attribute in Angular with the letter "x" is not permitted

After working with Angular 1.5.6 components, I came across a peculiar discovery. I have a component named scale which I call using the following syntax: <scale x-scale="xScale"></scale> In my controller, I set: $scope.xScale = 'lin&apos ...

Issue with handling 'this' in submit function in Sencha touch/JavaScript not resolved

I am currently working on developing a form using Sencha Touch that is designed to allow users to enter text and conduct a job search on a website. While most of the functionality is in place, including the reset button, I encounter an error when attemptin ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

Manipulate SVG elements using svg.js and svg-pan-zoom, allowing for double-click interactions

Using Ariutta's svg-pan-zoom with svg.js, I've disabled the native doubleclick functionality and implemented my own custom doubleclick behavior involving pan adjustment and animation. While this setup usually works fine, occasionally the doublec ...

Using jQuery to decrease the size of a div element containing an image

Hello everyone! I have an image inside a div and I am currently moving it down at a specific time using a delay. My question is, how can I make the image shrink as it moves down the screen until it eventually disappears completely at a set location? Curre ...

Python web scraping: Extracting data from HTML tag names

Seeking help with extracting user data from a website by retrieving User IDs directly from tag names. I am utilizing python selenium and beautiful soup to extract the UID specifically from the div tag. For instance: <"div id="UID_**60CE07D6DF5C02A987E ...

Adjust the background color of the unordered list when it corresponds to the current

Looking to customize a course calendar so that the day column stands out on its designated day of the week. For example, on Wednesday, the Wednesday column should have a distinct appearance. I've been experimenting with different methods and searchi ...

Can someone explain the significance of using the keyword "this" in JavaScript when it is referenced within an array?

When using the quojs javascript library, I often come across statements like these: return r(e,this[0].className) or return this[0].style[e]||n(this[0],e) While I understand that this refers to the "global object," I am curious about the significance ...

Is there a way to obtain background color values in decimal form?

I want to extract the background color in decimals that I have set, for example rgb(44.9, 19.373737, 255), using this jQuery code $("p").css("background-color") However, whenever I use it, the value gets rounded to rgb(45, 19, 255) All I need is to ret ...

Accessing the AppContext in Next.js within the _document file is the

My challenge with using next js is the occurrence of Content-Security-Policy issues due to the inline styles it utilizes. If 'unsafe-inline' is not added to the style-src, you will encounter the error message 'Refused to apply inline style ...