Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added.

    let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 );
    let mapOptions = {
      zoom: 13,
      center: myLatlng,
      scrollwheel: true,  

      }; 
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra BeachManly Beach Manly Beach Manly Beach', -33.950198, 151.259302, 1]
    ];

    let map = new window.google.maps.Map(
      document.getElementById("map"),
      mapOptions
    );


    var count;
    var markers=[];
    for (count = 0; count < locations.length; count++) {  
      markers.push(new google.maps.Marker({
      position: new google.maps.LatLng(locations[count][1], locations[count][2]),
      map: map,
      title: locations[count][0]
      }));
    }


    var infowindow = new google.maps.InfoWindow({
      content:"<div></div>"
      });

    markers.forEach(function(marker) {
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });
    });

Answer №1

In my opinion, updating your code to the following would be beneficial:

const locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra BeachManly Beach Manly Beach Manly Beach', -33.950198, 151.259302, 1]
];
let count;
let markers = [];

for (count = 0; count < locations.length; count++) {
  const myLatlng = new window.google.maps.LatLng(locations[count][1], locations[count][2]);

  const mapOptions = {
    zoom: 13,
    center: myLatlng,
    scrollwheel: true,
  };

  const map = new window.google.maps.Map(document.getElementById("map"), mapOptions);

  const marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: locations[count][0]
  });

  markers.push(marker);
}

const infowindow = new google.maps.InfoWindow({
  content: "<div></div>"
});

markers.forEach(marker => {
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
  });
});

markers.forEach(marker => {
  marker.setMap(map);
});

Answer №2

I've identified a few issues with your current approach:

  • You're initializing the map every time within the loop, which is causing only the last marker to show up.

  • You're attempting to bind events to only the last marker after the loop, whereas each marker should have its own event binding inside the loop.

To address these issues and get things working properly, consider the following suggestions:

  • Initialize the map once before adding markers to it.
  • Bind click events for each individual marker inside the loop.
  • Ensure info-window positioning using the latLng object.

For a functional demonstration, observe the code snippet below:

var locations = [
    ['Bondi Beach', -33.890542, 151.274856, 4],
    ['Coogee Beach', -33.923036, 151.259052, 5],
    ['Cronulla Beach', -34.028249, 151.157507, 3],
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
    ['Maroubra BeachManly Beach Manly Beach Manly Beach', -33.950198, 151.259302, 1]
];

var count, marker;

// Initialize the map
var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(locations[0][1], locations[0][2]),
    scrollwheel: true,
};

var map = new google.maps.Map(document.getElementById("map"), mapOptions);

// Create an info window
var infowindow = new google.maps.InfoWindow({
    maxWidth: 350,
    pixelOffset: new google.maps.Size(-10,-25)
});

var infoFn = function (count) {
    return function (e) {
        var content = '<div>' +
            '<span>Location: ' + locations[count][0] + '</span>' +
            '<span>, Lat: ' + locations[count][1] + '</span>' +
            '<span>, Long: ' + locations[count][2] + '</span>' +
            '</div>';

        infowindow.setContent(content);
        infowindow.open(map);
        infowindow.setPosition(new google.maps.LatLng(locations[count][1], locations[count][2]));
    }
};

// Add markers
for (count = 0; count < locations.length; count++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[count][1], locations[count][2]),
        map: map,
        title: locations[count][0]
    });
    marker.setMap(map);

    let fn = infoFn(count);
    google.maps.event.addListener(marker, 'click', fn);
}

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

Mastering the $emit function in Vue.js

Why isn't my VueJS emit working? I'm attempting to change a boolean value, but it's not emitting the change Here is the initial component: <template> <div id="reg"> <div id="modal"> ...

Tips for displaying a loader image with a centered message and preventing the bootstrap modal dialogue box from closing during an AJAX response from a PHP file

I am using Bootstrap version 3.0.0. Below is the HTML code for a Bootstrap Modal: <div class="modal fade" id="newModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> < ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Search for a specific key within a list of dictionaries

I am working with an array of dictionaries: arrayDict: [ { Description: "Dict 0" Category: [ 'First', 'Both', ], }, { Description: ...

Encountering a 401 error message with a 'truncated server' response while using Google Apps Script

I'm currently working on a code snippet that looks like this. function method3() { var spreadsheetID = '1BGi80ZBoChrMXGOyCbu2pn0ptIL6uve2ib62gV-db_o'; var sheetName = 'Form Responses 1'; var queryColumnLetterStart = ...

Using AJAX to Verify Google Recaptcha V3 Response

One of my functions is used to make an Ajax POST request : function ajaxPost(url, data, callback) { var req = new XMLHttpRequest(); req.open("POST", url, true); req.addEventListener("load", function () { if (req.status >= 200 && ...

What could be the reason behind CSS internal style not working while inline style is functioning properly?

Here is the code I am currently working with. It seems that there may be an issue, but I'm not sure what it could be. The first part contains internal CSS and below is inline CSS which appears to be functioning properly. My suspicion is that the image ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

Tips for utilizing state and city dropdown menus in JavaScript multiple times without interfering with other dropdowns

Currently, I am utilizing CodeIgniter to create a dynamic dropdown functionality. The setup involves four select country dropdowns where the state options will populate based on the selected country, and once a state is chosen, the corresponding city optio ...

inSession variable in express: set to false

i keep receiving inSession:false https://i.sstatic.net/4IW0f.png when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being ...

Determine the location based on the preceding parameter of $routeChangeError using AngularJS

I am currently monitoring events of the type $routeChangeError within a run block in my application. $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { if (!!previous) { console.log(previous); $locati ...

Value binding with conditional rendering in VueJS 2

My goal is to utilize VueJS 2 to render an inline condition while simultaneously adding a value to a DOM element. I am aware that I can use v-if to control the visibility of elements based on conditions, but how can I achieve an inline condition? For exam ...

Creating a custom regex script in Javascript to properly parse Google Sheets data that contains commas

Currently, I am working with a JavaScript script that extracts data from a public Google Sheets feed in a JSON-CSV format that requires parsing. The rows are separated by commas, but the challenge lies in dealing with unescaped commas within each item. Fo ...

Build a React application using ES6 syntax to make local API requests

I'm really struggling to solve this problem, it seems like it should be simple but I just can't figure it out. My ES6 app created with create-react-app is set up with all the templates and layouts, but when trying to fetch data from an API to in ...

A step-by-step guide on utilizing moment.js to format the data provided by a vuetify v-text-field (with the type: time)

Currently, I have set up this element in the code: <v-text-field label="Choose a time" type="time" mask="time" step="1800" prepend-inner-icon="access_time" v-model="expiryTime" :rules="[v => !!v || 'Time is required']" requ ...

Organizing various elements into separate divs with just one ajax request

I recently encountered an issue with my project involving an ajax call that was functioning correctly. $.get( 'accNoRealMovs1.jsp', {mode:"0"}, function(responseText){ $('#divAccMovementNR').html(responseTe ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...

Is checking for an email address in a form necessary?

I am currently in the process of creating a coming soon page. I have included a form on the page where users can sign up using their email addresses, which are then sent to me via email. However, I need assistance in determining how to verify that the in ...

What is the best way to halt a CSS transition using JavaScript when dealing with an image?

I am facing an issue while attempting to create a basic CSS transition using JavaScript. The goal is for the start button to trigger the movement of an element, based on the duration of the keyframe animation. Then, clicking the end button should make the ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...