Positioning the infowindow in Google Maps API v3

Creating a map with various markers, each with its own info window. However, when attempting to display an info window on multiple markers, the position remains fixed at the first clicked marker. What could be causing this issue?

<script type="text/javascript">
      function initialize() {
        var latlng = new google.maps.LatLng(53.033117,5.639752);

        var latingSiton = new google.maps.LatLng(53.0356197730161,5.62613738302669);
        var SitonImg = 'images/siton.png';
        var latingZee = new google.maps.LatLng(53.0360534900284,5.62488617774811);
        var ZeeImg = 'images/zee.png';
        var latingHylkema = new google.maps.LatLng(53.0373853769166,5.62924255777811);
        var HylkemaImg = 'images/hylkema.png';
        var latingDijkstra = new google.maps.LatLng(53.0360125088934,5.62735529113307);
        var DijkstraImg = 'images/dijkstra.png';

        var myOptions = {
          zoom: 16,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

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

        var contentString = 'test';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

          var marker = new google.maps.Marker({
              position: latingSiton, 
              map: map, 
              icon: SitonImg,
            });

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

          var marker = new google.maps.Marker({
              position: latingZee, 
              map: map, 
              icon: ZeeImg,
          });

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

          var marker = new google.maps.Marker({
              position: latingHylkema, 
              map: map, 
              icon: HylkemaImg,
          });

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

          var marker = new google.maps.Marker({
              position: latingDijkstra, 
              map: map, 
              icon: DijkstraImg,
          });

          google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
            });
        }
    </script>

Any suggestions would be greatly appreciated!

Answer №1

If you're looking for an alternative to Pratik's recommendation, give this a try:

let locationMarker = new google.maps.Marker({
     position: siteLocation,
     map: map,
     icon: customIcon
});

// Make sure to include this line each time a new marker is added:
attachInfoWindow(locationMarker, map, infowindow);

Next, define a new function:

function attachInfoWindow(locationMarker, map, infowindow) {
    locationMarker.addListener('click', function() {
        infowindow.open(map, locationMarker);
    });
} 

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

Divide and Insert a Gap in Phone Number

I need help formatting a telephone number so that there is a space between every third and seventh character. var phoneNum = "02076861111" var formattedNum = [phoneNum.slice(0, 3), phoneNum.slice(3,6), " ", phoneNum.slice(6)].join(''); console ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

url-resettable form

Currently, I am working on an HTML form that includes selectable values. My goal is to have the page load a specific URL when a value is selected while also resetting the form back to its default state (highlighting the "selected" code). Individually, I c ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

Issue: Unauthorized access: nodeMailer despite correct configuration

Having trouble with an error when using the less app option on Gmail. I don't have 2-factor authentication enabled, and my credentials are correct. I can log in to my file to verify this, but the error still persists. const nodemailer = require(" ...

The issue of the "port" attribute not working for remotePatterns in the Image component has been identified in Next.js 13's next.config.js

I've encountered an issue with the code snippet below. I'm attempting to utilize remotePatterns in my next.config.js file to enable external images. Strangely, when I set the port to an empty string "", it functions correctly. However, specifying ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...

Creating Secure JWT Tokens

Hello there! I'm currently in need of assistance with generating JWT tokens that include three headers: alg, kid, and typ. The format I am looking for is as follows: { "alg": "RS256", "kid": "vpaas-magic-cookie-1 ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

Making a Call with Twilio using Node.js

Currently, I am working on a click-to-call website that is powered by Twilio. The process involves configuring a TwiML app and writing Twilio JavaScript SDK client-side to send requests to Twilio. Once this is done, Twilio will initiate a POST request to t ...

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

How can I limit the radius of a circle in Angular Google Maps?

I am utilizing angular-google-maps and attempting to limit a circle's radius. For example, when the radius_changed event is triggered, I check the radius value and if it's less than 100, I set it to 100. Unfortunately, this approach doesn't ...

Ensure that PHP form validations are checked when submitting the form using jQuery

I have created a form in HTML with basic verification. Here is the code: <form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form"> <input class="form- ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

Send a request from my own local client without encountering any Cross-Origin Resource Sharing (C

I am attempting to send a request from my locally hosted Node.js/Express.js client to a third-party API that I have deployed on the cloud. Strangely, I keep running into a CORS error whenever I make the request. The interesting part is that the request wor ...

Remove files from the server using an AJAX request

I am attempting to delete files on the SERVER using JavaScript, and I have already consulted the advice provided in this JavaScript file deletion thread My current JavaScript code looks like this: deleteFile = function() { return $.ajax({ url: "de ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Puppeteer exhibiting unexpected behavior compared to the Developer Console

My goal is to extract the title of the page using Puppeteer from the following URL: Here's the code snippet I am working with: (async () => { const browser = await puppet.launch({ headless: true }); const page = a ...

Converting a blob to base64 and then back to a blob in Node.js may result in varying sizes between the two

I am currently implementing this code in a Node.js application. I have a blob that I am converting to a base64 string and then back to a blob using the following method: // Converting Blob to base64 string via Buffer const buffer = Buffer.from(await myBlob ...

Loop through each div using jQuery and dynamically add or remove a class to

I am looking to create an infinite loop that adds a class to each div with a timeout in between. Currently, I have implemented it like this: $(document).ready(function() { $('.small-bordered-box').each(function(i) { var $t = $(this); ...