Struggling to link different InfoWindows to various Markers on a Google Map without success

My latest project involves utilizing a JSON feed to retrieve earthquake data within specified latitude and longitude boundaries, essentially creating a defined area. The information gathered is then used to mark locations on a Google map. Each marker is intended to provide additional details when clicked, so I have been working on implementing InfoWindow objects to display relevant information associated with each marker. However, I have encountered an issue where clicking on any marker always opens the same InfoWindow above one specific marker in that group. It seems that the last created InfoWindow in my loop is consistently being displayed. Below is the code snippet:

$.getJSON(url, function(jsonData) {
    for(var i = 0; i < jsonData.earthquakes.length; i++) {
        var position = new google.maps.LatLng(jsonData.earthquakes[i].lat, jsonData.earthquakes[i].lng);
        var infoContent = jsonData.earthquakes[i].lat + ", " + jsonData.earthquakes[i].lng;
        var newMarker = new google.maps.Marker({
            map: map, 
            position: position,
            title: jsonData.earthquakes[i].eqid
        })
        
        var newTooltip = new google.maps.InfoWindow({
            content: infoContent
        })
        
        google.maps.event.addListener(newMarker, 'click', function() {
            newTooltip.open(map, newMarker);
        });
        
        markersArray.push(newMarker);
        tooltipsArray.push(newTooltip);
    }               
});

The markersArray stores all marker objects on the map, while tooltipsArray holds the InfoWindow objects. Both arrays are global variables.

Answer ā„–1

This question about Google Maps frequently arises in the google-maps tag and is an easy mistake to make :).

The issue at hand is that your click event is being triggered asynchronously, capturing the current value in the marker variable within the getJSON callback (the final one in the list).

To resolve this, it's necessary to enclose your addListener call within a function to establish a closure around the marker variable utilized in the click callback:

function listenMarker (marker)
{
    // ensures marker is associated with the closure created during the listenMarker function invocation
    google.maps.event.addListener(marker, 'click', function() {
                        tooltip.open(map, marker);
                    });
}

Subsequently, invoke listenMarker from your primary getJSON callback (where you're currently invoking addListener).

Answer ā„–2

If you want to simplify the process, you can try the following approach:

// By linking "this" with marker in the addListener call,
// tooltip will open at the location of the marker when clicked
google.maps.event.addListener(marker, 'click', function() {
                    tooltip.open(map, this);
                });

Simply replace "marker" with "this" in the addListener function to streamline the code and avoid creating unnecessary functions.

For a more comprehensive solution and demonstration, be sure to check out the full guide!

Answer ā„–3

By encapsulating the addListener call in a separate function, we can prevent multiple infowindows from displaying identical text.

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

Working with Garber-Irish in Rails: Streamlining Administration and Keeping Code DRY

I am currently implementing the innovative garber-irish technique to organize my JavaScript files. Here's my issue: I have a Model (let's call it Item) with an init function located in app/assets/javascripts/item/item.js For example: MYAPP.ite ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

What steps are involved in linking an on-premises Webapi service and WCF Service with our asp.net application on Azure?

Looking to connect our existing on-premises webApi, WCF, and Web Services with Azure. Seeking recommendations for integrating these services seamlessly. Any ideas or suggestions? ...

flake picks up blank value from JSON file stored in AWS S3

It should be a simple task, but on a Friday night, I'm struggling... Currently, I'm working with a json file stored in s3 {"name":"bob", "currentTime":"null"} I've set up a stage in snowflake. When ...

Utilizing jQuery for animating SVG elements with dynamic color changes and scaling effects upon hover

Seeking assistance from coding experts! I have created an icon and am attempting to modify it so that the color changes when hovered over. Additionally, I want the white square to scale down by 50% starting from the top-left corner of its current position. ...

Picture is currently not showing up in the division

I am currently working on an HTML page and I'm having trouble displaying an image within a division element. Below is the code snippet I tried: Here is the JavaScript part of my code: var filename = "andrew.png"; $("#detected").show().html('< ...

The jQuery scrollTop feature seems to be malfunctioning

My code is causing an error that I don't understand. Any help would be appreciated... I'm getting the following error message: Property does not exist on type '.js--section-plan'.ts(2339) when I hover over the offset() in vscode $(&apos ...

"Encountered difficulty reading the data from the downloaded blob due to a problem

How can I check the internal buffer to see if my text data is present? Am I using node.js' Stream.read() correctly? I have a text file stored as a blob on azure-storage. After downloading the blob, I receive a readable stream along with information a ...

Having trouble fixing the GAE Python error "Client_secrets.json file not found" in your app.yaml file?

Currently, I am working with GAE (python) to develop a web application. My main focus is on integrating the youtube API, but I seem to be encountering issues with the credentials not functioning correctly. Whenever I attempt to follow the "Retrieve my Upl ...

Error: The object being used with the 'in' operator is not valid

data = new Gson().toJson(name); where name is a string value. An error message is appearing stating "TypeError: invalid 'in' operand obj " The issue seems to be in the specific part of the JavaScript code: return type === "array" || type !== ...

Gson was expecting an object to begin but instead encountered a string... however, the type of value keeps changing in

My journey to learn Android involves building an app that utilizes the lastFm API to fetch similar songs. I have chosen to work with retrofit2, Gson, and rxJava for this project. In order to handle the JSON response effectively, I have implemented POJO cl ...

Is a directive necessary for a search element in this component?

I am currently learning angularJS and although it would be simpler to use JQuery for this task, I am determined to do it the right way. Essentially, I want to create a text input field where users can type in a search term, press a search button, and then ...

Toggle Radio Button List Item Visibility with JavaScript

I am trying to achieve a functionality where if a user selects a certain option from a dropdown list, it will hide or display specific items in a radio button list. For example, if the user chooses "Opt2" from ddlTest, I want to hide rblItem3. Can someon ...

Unusual shadow effects with three.js

I'm still new to three.js and webgl, and I'm encountering some odd-looking shadows when using a directional light. Could somebody help me out? Below is the code I have for the renderer: this.renderer.shadowMapEnabled = true; this.renderer.shad ...

Move the div from side to side when clicked

My mobile navigation bar currently has overflow, requiring users to scroll left or right to see all the choices. I want to implement buttons with arrows that will automatically slide the navigation bar to the desired direction when clicked. I have attempt ...

Leveraging the Meteor Framework for Application Monitoring

Exploring the potential of utilizing Meteor Framework in a Monitoring Application. Scenario: A Java Application operating within a cluster produces data, which is then visualized by a Web Application (charts, etc.) Currently, this process involves using ...

Adding distinct objects in React.js

Currently experimenting with building an e-commerce application using React just for fun. Iā€™m facing a challenge in setting state on a specific object as it gets added to an array. My scenario involves an array called cart where items selected from the ...

The dropdown change event in jQuery does not populate the textarea field

Seeking assistance from the community. I am facing an issue with a form that includes a drop down list alongside the TinyMCE editor. Upon selecting an item from the drop-down list, the content does not populate in the TinyMCE editor textarea. Instead, an ...

What steps can be taken after the addClass function has been triggered?

I am trying to achieve a functionality where upon clicking a button, a div will add a class that changes its width to 150px. However, I want something to be shown in console.log only after the div has become 150px in width. Can anyone assist me in achievin ...

What is the best way to display a Bootstrap success message within the Ajax success function()?

Utilizing the below jQuery/Ajax approach for form validation. Sending json data to the add.php PHP file. If any errors are found on the add.php page, an error message is displayed; otherwise, a success message is shown. In the ajax success method, I aim t ...