Categories
JavaScript Answers

How to make Google maps responsively resize with JavaScript?

Spread the love

Sometimes, we want to make Google maps responsively resize with JavaScript.

In this article, we’ll look at how to make Google maps responsively resize with JavaScript.

How to make Google maps responsively resize with JavaScript?

To make Google maps responsively resize with JavaScript, we add a resize event listener.

For instance, we write

let map;

const initialize = () => {
  const mapOptions = {
    center: new google.maps.LatLng(40.5472, 12.282715),
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
};

google.maps.event.addDomListener(window, "load", initialize);
google.maps.event.addDomListener(window, "resize", () => {
  const center = map.getCenter();
  google.maps.event.trigger(map, "resize");
  map.setCenter(center);
});

to define the initialize function that creates the map.

We create a Map object from the element we get with getElementById.

Then we call addDomListener to listen for window resize by calling it with window and 'resize'.

And then we call trigger and map and 'resize' to resize the map when the screen resizes.

Conclusion

To make Google maps responsively resize with JavaScript, we add a resize event listener.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *