The InfoWindow in Google Maps API v3 initially displays in the wrong position before loading in the correct location

Take a look at this page

Upon loading the map, there seems to be an issue where the InfoWindow initially appears on the left edge before quickly transitioning to the correct center position. Is there a way to ensure that the InfoWindow is always centered when the map loads? It appears that the transition could be smoother and more seamless, is there a problem with my code causing this rough transition?

<div id="map-canvas"></div>
    <script>
        function initialize() {
            var myLatlng    = new google.maps.LatLng(29.950217, -90.075517);
            var centerPos   = new google.maps.LatLng(29.952365, -90.075853);
            var mapOptions  = {
                        zoom        : 15,
                        center      : centerPos,
                        styles      : [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"administrative","elementType":"labels","stylers":[{"saturation":"-100"}]}]
                    };

            var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            //content within the popup
            var contentString = '<div id="mapContent">'+
                        'Place your content here'+
                        '</div>';

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

            //the marker on the map
            var marker = new google.maps.Marker({
                position    : myLatlng,
                map         : map,
                title       : 'Marker Title'
            });
            
            //when clicking the marker, open the info window
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

            // Resize stuff...
            google.maps.event.addDomListener(window, "resize", function() {
                var center = map.getCenter();
                google.maps.event.trigger(map, "resize");
                map.setCenter(center);
            });

            //auto open info window
            infowindow.open(map,marker);
        }

        google.maps.event.addDomListener(window, 'load', initialize);
        // end google maps 
    </script>

Answer №1

Trigger the infowindow display automatically when the map becomes still:

//open info window
google.maps.event.addListenerOnce(map, 'idle', function () {
    google.maps.event.trigger(marker, 'click');
});

JSFiddle demo

Sample code snippet:

function initialize() {
  var myLatlng = new google.maps.LatLng(29.950217, -90.075517);
  var mapOptions = {
    zoom: 15,
    center: myLatlng,
    styles: mapStyles
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  //content for the infowindow
  var contentString = '<div id="mapContent">' +
    '<div id="siteNotice">' +
    '</div>' +
    '<h1 id="firstHeading" class="firstHeading">Blanchard Systems</h1>' +
    '<div id="bodyContent">' +
    '<p><a href="https://maps.google.com?daddr=Blanchard+Systems+1100+Poydras+Street+New+Orleans+LA+70163">Click here for directions</a>' +
    '<p><b>Address:</b> 1100 Poydras Street, New Orleans, LA 70163. Suite 1230.</p>' +
    '</div>' +
    '</div>';

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

  //marker on the map
  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Blanchard Systems'
  });

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

  // Resize stuff...
  google.maps.event.addDomListener(window, "resize", function() {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center);
  });

  //auto open infowindow
  google.maps.event.addListenerOnce(map, 'idle', function() {
    google.maps.event.trigger(marker, 'click');
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
var mapStyles = [...]
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>

Answer №2

Ensure to insert position: centerPos, above content: contentString.

It's recommended to eliminate

var myLatlng = new google.maps.LatLng(29.950217, -90.075517);
as it has already been defined with centerPos. Remember to update position : myLatlng, to position: centerPos, inside your marker variable if you decide to remove myLatLng.

Snippet

function initialize() {
  var centerPos = new google.maps.LatLng(29.952365, -90.075853);
  var mapOptions = {
    zoom: 13,
    center: centerPos,
    styles: [ ...... ];
	};

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  //the marker on the map
  var marker = new google.maps.Marker({
    position: centerPos,
    map: map,
    title: 'Blanchard Systems'

  });

  //content within the popup
  var contentString = '<div id="mapContent">' + ..... ;


  //the info window
  var infowindow = new google.maps.InfoWindow({
    content: contentString,
    position: centerPos,
  });

  //when clicking the marker, open the info window
   ......
}

initialize();
  html,
  body,
  #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
  }
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

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

Tips for maintaining the state of my jQuery accordion menu on my website even after refreshing the page

I came across a nested JQuery accordion code that works perfectly, but there's a major issue. When I click on a menu or submenu in my sidebar (a link that redirects to a different URL), the site fails to remember which menu or submenu should be shown ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Move files into the designated folder and bundle them together before publishing

Is there a way to transfer the files listed in package.json (under the File field) to a specific folder in order to bundle them together with npm publish? Here is the structure of my repository: . ├── package.json └── folder0 ├── fil ...

Passing a table value to a PHP script using JQuery on click event

I am struggling with implementing functionality to filter a dataset based on the link that the user clicks on within a bootstrap modal. The modal contains a morris.js graph and I need to pass the clicked value (e.g. Cluster1 or Cluster2) to a data pull scr ...

I'm experiencing an "existing database with different casing already exists" error, even though I have no intention of creating a new database

My goal is to include a new word in a database called "wordsDb" within a collection named "wordsCollection": dbName = "wordsDb"; collectionName = "wordsCollection"; connectionUri = //... (secret) async add(word) { try { ...

What are the steps to create a basic popup dialog using minimal html, css, and javascript code?

Is it possible to create a contact form popup on the home page within a lightbox? I have managed to display the contact form on the home page, but I am struggling to get the desired grey background for the lightbox effect. Can anyone assist me with this? ...

Leveraging the power of JavaScript and possibly regular expressions to extract numerical values from a

I am attempting to extract a variable number from the text provided in the following example: Buy 5 for € 16.00 each and save 11% Buy 50 for € 15.00 each and save 17% Buy 120 for € 13.00 each and save 28% Buy 1000 for € 10.00 each and save 45% Th ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Concentrating on a Div Element in React

I'm trying to set up an onKeyPress event that will be triggered when a key is pressed while a 'Level' element is displayed. I know that the div needs to be focused for events to register, but I'm not sure how to do this with functional ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html: <button type="button" class="b ...

How can you integrate Dygraph into your React project alongside redux?

Lately, I've been facing some challenges while trying to integrate Dygraph into React (utilizing Redux). The Dygraph wrapper packages available on NPM don't seem to cooperate. Furthermore, the conventional method of using: <div id="graph"> ...

A guide to resolving the "ActiveRecord::RecordNotFound" error in Rails for a missing Program ID

While conducting an initial test of my Rails API, I encountered an issue when trying to fetch data from my backend and display the results using console.log() in my browser console. The problem arose when attempting to access a list of programs through my ...

Transform post-back into PHP using JSON for Ajax posting

Currently, I am facing a challenge in integrating a Codeigniter application into Wordpress using a plugin. The trouble arises when the control encounters an issue while confirming the data for a new appointment. VIEW <div id="wizard-frame- ...

Using the theme object in makeStyles in Material UI without requiring a ThemeProvider – a step-by-step guide!

My custom theme object is structured as follows: import palette from './palette'; import typography from './typography'; const theme = createMuiTheme({ palette, typography, })); export default theme; When using MUI, useStyles() ...

The parameter 'Value | ValueXY' cannot be assigned to the type 'AnimatedValue<0>'

Recently, I delved into React Native documentation on Animations which can be found here: https://reactnative.dev/docs/animated After reading the docs, I decided to try out some code snippets: import {Animated as RNAnimated} from 'react-native' ...

Tips for effectively invoking functions upon a page being loaded?

I am currently working on adding pagination feature to manage the number of quotes displayed in my Vue.Js application. I have created a function that divides the quotes based on the paginationLimit value. However, I am encountering an issue where the updat ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

Ensuring that the callback of one function is executed only after the callback of the second function is a crucial step in maintaining the proper sequence

I am in the process of extracting data from a PDF table using JavaScript. The PDF I am working with is a university timetable displayed as a grid with information in each grid cell. I am currently utilizing the pdfreader npm package for this task (although ...

What is the recommended location to put clearTimeOut?

Attempting the following var timeoutId = setTimeout(function() { if ("comboFilters[Agencies]" in partDic) { var agency = partDic["comboFilters[Agencies]"].substring(1); $('.Agency .dropdown-toggle').html(agency).append(' ...