I'm looking to add multiple markers with multiple info windows using the Google Maps API. How can I achieve this?

Having trouble with the Google Maps API v3? I've set up a map with custom markers, but when clicked they all display the same content in the info window. Can you take a look at my code and help me troubleshoot? Each marker is supposed to link to a specific webpage related to that location, but I seem to be running into some issues. Any assistance would be greatly appreciated!

<!doctype html>
<head>

...

</script>
</head>
<body onload="initialize()">

<div id="header">
    <div id="headercon">
        <a href="http://www.linux4hope.org">
            <div id="headerwrap"></div>   
        </a>        
    </div>
</div>

<div id="map_canvas"></div>

</body>

</html>

Answer №1

To avoid overwriting, consider using unique names for both the marker and infowindow elements.

One approach could be to utilize an array to hold the data (latitude/longitude, title, content) and then dynamically create the markers and windows within a loop.

Answer №2

The issue at hand stems from the reusing of variables in your code. The click event handlers are all anonymous functions that do not execute until the event is triggered. Once these functions run, they encapsulate the scope of the surrounding functions. Due to the reuse of variable names, the values for all infowindows except the last one get overwritten, resulting in only the final infowindow being displayed.

To address this, you could opt for separate variables for each location:

var marker1,infowindow1,marker2,infowindow2, ...

However, a more efficient solution would be to construct a data structure containing positions and their corresponding infowindows.

var locations = {
'London' : {
 marker : new google.maps.Marker({ ... }),
 infowindow : new google.maps.InfoWindow({ ... });
},
'Manassas' : { ... }

This way, you can iterate through the data structure and link each marker with its respective infowindow seamlessly.

Answer №3

The reason for this issue is that all the event handlers are triggering at the same time, causing all the infowindow variables to point to the same object. To resolve this, you can implement some simple solutions such as renaming the variables (e.g., infowindow1, infowindow2, etc.) or adding more closures:

(function(){
    var marker = new google.maps.Marker({
        position: London, 
        map: map,
        title:"Linux4Hope UK",
        icon: 'http://static.tumblr.com/asviked/U1flr229o/marker.png'  
    });   

    var infowindow = new google.maps.InfoWindow({
        position: London, 
        content: '<p><a href="http://www.linux4hope.org.uk">Linux4Hope, London, United Kingdom</a></p>'
    });

    google.maps.event.addListener(marker, 'click', function() {
        position: London, 
        infowindow.open(map, this);
    });
})();

Alternatively, you can try:

google.maps.event.addListener(marker, 'click', function(iw){
    return function() {
        iw.open(map, this);
    };
}(infowindow)
});

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

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Step-by-step guide to launching a new window or tab without automatically bringing it into focus

Is it possible to use JavaScript to open a URL in a new tab without giving that tab focus on a click event? ...

Vue select is causing the selected choice of another selector to be influenced

Currently, I am facing an issue with a table displaying a specific Nova resource. The problem lies in the selectors within each row of the table - when one selector is changed, all other selectors automatically mirror that change. This behavior seems to be ...

Replacing multiple attributes within a complex HTML opening tag using Node.js regular expressions

I'm currently working on a Node.js project where we need to search through several PHP view files and replace certain attributes. My goal is to extract the values of HTML open tag attributes and replace them. To clarify, I want to capture anything in ...

Setting nodeIntegration to false led to an Uncaught ReferenceError: require is not defined when trying to access Object.url (external "url":1) in the electron-react-typescript environment

After setting nodeIntegration to false, I encountered the following error message: "Uncaught ReferenceError: require is not defined at Object.url (external 'url': 1)". https://i.sstatic.net/galzh.png Upon clicking on the link referring to "exte ...

Adjusting image size according to browser dimensions

I've been struggling to resize a background image on my Square space website dynamically based on the user's browser window size. If the window width drops below a certain point, I want the image to adjust accordingly while maintaining its aspect ...

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

The 'api' property is not found within the 'MyService' type declaration

Currently, I am working on a tutorial where we are building an Angular service to send emails from a form using the Mailthis Email API. In the code for the service, I encountered an error related to the 'api' variable that states "Property ' ...

Listening on TCP port for HTML5 Websocket communications

I have a desktop application that is communicating with my asp.net mvc app. The desktop application publishes data on port:10000 which I need to be able to listen to in the browser. Below is the code snippet: <html> <head> <s ...

Match rooms using Socket.io

I am utilizing the opentok and socket.io packages in an attempt to establish 2 distinct "groups". Successfully, I have managed to pair up individual users in a 1-to-1 relationship. However, my goal is to create two separate groups of users. For instance, ...

Implementing TestCafe with a Rails backend and utilizing fixtures data for testing

Currently, I am involved in a Rails project that utilizes RSpec for testing. We rely on various Rails fixture data to test our UI under different conditions. Recently, I came across TestCafe for handling functional UI testing, and I find it quite intrigui ...

Establish communication between two Sails applications

I am currently working on a Sails.js project that features a member portal with all possible routes and actions. However, I am considering developing a CMS using Sails as well. Originally, my plan was to integrate the CMS into the existing project, but n ...

Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

Pause the audio using jQuery when the slide changes

I have a Drupal website with a slider that includes an audio player on each slide. I need the audio to stop whenever the slide changes. The slider plugin I'm using is owlCarousel. Here is my current code: $("#owl-demo").owlCarousel({ afterAction: ...

Encountering an issue when attempting to construct the project: it asks for callback functions, but instead received an [

I'm currently facing an issue while trying to access a function that is crucial for updating some database values. Whenever I attempt to build the project, I encounter the following error: Error: Route.post() requires callback functions but got a [ ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

Difficulty in sharing cookies among subdomains

I have successfully stored my visitors' style sheet preference in a cookie, but I am facing an issue with sharing the cookie across subdomains. Even after specifying the domain, the cookie does not seem to be shared. What could be causing this proble ...