How to automatically center Google Maps and update marker on responsive resize

Trying to figure out how to maintain the center of Google Maps while resizing responsively has been a challenge.

I've successfully centered the map, but I'm struggling to include my marker in the JavaScript code so that it stays centered as well. The map centering code is based on this source: Google maps responsive resize

var map; //<-- Accessible to both event listeners and initialize() function
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(LAT,LNG),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        scrollwheel: false,
        keyboardShortcuts: false,
    };

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

google.maps.event.addDomListener(window, 'load', initialize);

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

The snippet above shows the code used for centering the map. The following excerpt includes the marker code, but integrating it properly for maintaining the center position remains a puzzle.

var marker = new google.maps.Marker({
        position: new google.maps.LatLng(LAT,LNG),
        map: map,
        title: 'Title',
        animation: google.maps.Animation.DROP,
        })
    }

If anyone can offer assistance with this issue, it would be greatly appreciated.

Answer №1

To begin achieving your goal, follow these initial steps:

var map; //This variable is now accessible to both event listeners and the initialize() function
var mapCenter; // Initialize a variable for storing the map center
var centerMarker; // Define the marker

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(LAT,LNG),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        scrollwheel: false,
        keyboardShortcuts: false,
    };

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

    // Create a new marker and display it on the map
    centerMarker = new google.maps.Marker({
        position: new google.maps.LatLng(LAT,LNG),
        map: map,
        title: 'Title',
        animation: google.maps.Animation.DROP
    });

    mapCenter = map.getCenter(); // Set the loaded map's center as the variable value
}

google.maps.event.addDomListener(window, 'load', initialize);

google.maps.event.addDomListener(window, "resize", function() {

    // Adjust the map center using the stored value in "mapCenter"
    map.setCenter(mapCenter); 
});

Note: As suggested by @Chad Killingsworth, consider adding an 'idle' event handler to update the mapCenter variable. Here's how you can do that:

google.maps.event.addListener(map,'idle',function(event) {
    mapCenter = map.getCenter();
});

Explanation of the 'idle' event according to the documentation:

This event triggers when the map stops moving after panning or zooming.

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

Automatically submitting a Google Form using the Google Forms API in conjunction with Google Apps Scripts

Is it possible to integrate a third-party app with Google Forms API and Google Apps Script in order to create timed quizzes that automatically submit once the time limit has been reached? ...

Tips for making an input form that triggers an alert popup

After creating an HTML form with text input, utilizing Javascript for validation as shown below: I am trying to trigger an alert box thanking the user for entering data when the submit button is clicked. I have faced challenges in implementing this witho ...

What is the most effective way to display multiple variables simultaneously in Mongoose/Node.js?

As a newcomer to programming, my initial major project involves building a website using Mongoose and Node.js. I have a query regarding rendering two variables for ejs simultaneously without encountering an error due to attempting to render a query that h ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

The usage of the enzyme shallow() function combined with the addition of event listeners

A specific component is causing some issues in my application: class ProblematicComponent extends Component { componentDidMount() { this.monitorForClicks(); } monitorForClicks() { this.elementRef.addEventListener('click', () => ...

Discovering which page the form was submitted from using xsl template

Incorporating code like <input type="hidden" value="contact-form-1" name="getpage"> into my form is something I'm interested in, as it allows me to retrieve the URL of the page from which the form was submitted. The challenge arises because the ...

Is there a way to optimize Typescript compiler to avoid checking full classes and improve performance?

After experiencing slow Typescript compilation times, I decided to utilize generateTrace from https://github.com/microsoft/TypeScript/pull/40063 The trace revealed that a significant amount of time was spent comparing intricate classes with their subclass ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Maximizing CSS opacity for optimal performance in image fading

I'm working on creating a smooth fade in-out effect for the images in my photo gallery by adjusting the CSS opacity value using JavaScript. However, I've noticed that this process is quite sluggish on certain computers, such as my relatively new ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

Creating a clickable map for a PNG image: Step-by-step tutorial

My goal is to create a interactive map similar to this one. Click here for the image ...

Implementing JavaScript to assign a symbol to several <span> elements with identical ids

I have a looping span element on my page that is generated based on the number of records in a database table. The appearance of the span can vary, displaying either one or multiple instances. Each span has the following structure: <span class="add-on" ...

Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

I’m struggling to figure out how to use $http.get in AngularJS to pass filter parameters. The URL is: http://localhost:8080/template/users/query;username=abcd;firstName=ding... The RestController looks like this: @RequestMapping(value={"/users/{query ...

What happens to CSS specificity when JavaScript is used to change CSS styles?

When JavaScript modifies CSS, what is the specificity of the applied styles? For example: document.getElementById("demo").style.color = "red"; Would this be deemed as inline styling? ...

Tips for setting a default value in an input type file using JavaScript

While trying to upload a file from my local system to the server, I encountered an issue where the local path was not being set in the input type file field. As a result, I am unable to successfully upload the file. I would greatly appreciate any assistan ...

When I incorporate JavaScript logic into my navigation, the Anchor Links fail to work properly

Currently facing an issue with my navigation bar where the category jump labels should change their bootstrap class when the corresponding heading is visible in the viewport. While everything works fine up to this point, adding the second event listener fo ...