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

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

Using JavaScript to send formatted text through POST requests in a Rails application

Within APP A, I have the following formatted text: A beautiful painting because I created it because an artist endorsed it because my cat loves it I can access this formatted text in index.html.erb through product.body_html, which I then load into a Ja ...

What are some possible reasons or solutions for Axios sending a 404 error?

Hi there, I'm completely new to the MERN stack and I'm encountering an issue when trying to post data using Axios and Express. I may have misunderstood something, so here's my problem. I have a form on a page that I am attempting to use to s ...

Angular.js: The Best Way to Attach a "Change" Event to a Service

Just starting out with angular.js... I have a HTML5 page where I can input new URLs along with names. Now, I need to validate these URLs against a back-end service to see if they already exist. How can I trigger the “onChange” event on the input field ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

Tips for moving and filling data in a different component using NextJS

Currently, I am developing an application using Next.js and tailwindcss. The Issue In essence, I have a table consisting of 4 columns where each row contains data in 3 columns and the last column includes an "Update" button. The data in each row is genera ...

What is the mechanism behind declaring a function using square brackets in Node.js/Javascript?

Encountering something new while working with Node.js - a unique way of declaring functions. You can find an example at this link. 'use strict'; const Actions = { ONE: 'one', TWO: 'two', THREE: 'three' }; clas ...

Unusual sequence of JQuery Ajax calls

Within my website, there is a project div that is displayed using EJS. The data for the projects in EJS are rendered using a forEach loop, resulting in multiple similar divs appearing on the page. Each project div is assigned an id for identification pur ...

An innovative countdown clock for WooCommerce that dynamically displays delivery time as a customizable shortcode

After successfully creating a Wordpress shortcode with a JavaScript counter, I encountered an issue: Back End - Counter functions properly: https://i.stack.imgur.com/qyHIL.png Front End - Counter not working (no console errors...): https://i.stack.imgu ...

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

Obtaining the final field with the $in operator in Mongoose

I need to retrieve all person records that fall within a time frame specified by start and end dates, and have a place ID of either 1 or 2. Below is the query I am using: Person.find({ time: { $gte: start, $lt: end ...

Using ngModel instead of value to bind a custom Angular directive for currency input

Currently, I am using a specialized mat-input-currency format directive to automatically convert my field inputs into currency. You can find the npm repository here. However, the directive binds the element data to [value] of the input, and I require it t ...

The method defined in user.model.js cannot be utilized in mongoose and node

When developing an app with node and mongoose, I encountered a peculiar issue while testing. Below is my auth.index.js file for user login. auth.index.js: var express = require('express'); var mongoose = require('mongoose'); var passp ...

Troubleshooting the problem of fast rotation and scrolling of text in the middle but slow movement at the end with

Currently, I am utilizing the jquery animate function for animating text while also aiming to rotate the text if a specific degree is passed. In order to achieve this, I have implemented the following code snippet: var leftCss = "-"+$('#mydiv'). ...

Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue? Previously, I attempted to retrieve the location by using the axios ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

What is the best way to include multiple entries in a select2 form using ajaxform?

select2/3.5.2/ I had to repost this because my initial post was not formatting correctly. The tools in use are: A select2 form field that allows searching through multiple records A bootstrap popup modal containing a form for entering a new record if i ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

I am encountering an issue where propData in Vue Jest is returning as undefined

I have encountered an issue while passing the propData in my jest test file for a Vue component. It seems that the propData is not being set to the component and instead, I am receiving an error saying "cannot read property of clouds of undefined." Could i ...