Last Updated: January 25, 2018
· neutralino1

Auto-center and auto-zoom a Google Map

If you display a Google Map on your site using the Google JS API, here is how you can have it auto-centered and auto-zoomed depending on the markers it contains.

Before adding markers:

bounds  = new google.maps.LatLngBounds();

Everytime you add a new marker:

loc = new google.maps.LatLng(, marker.position.lng());

After all markers have been added:

map.fitBounds(bounds);       # auto-zoom
map.panToBounds(bounds);     # auto-center

That's it, cheers.

5 Responses
Add your response

Very useful tip. Google maps can be such a pain due to the extensive and unorganised documentation.

over 1 year ago ·

thank's for the code it's really very useful. I add those lines to my code but it doesn't work for the first time , I should reload page every time before the map is showing correctly help please! I use the code of ajax php mysql from google maps api to generate my map

over 1 year ago ·

Nice. Thanks. This worked first time. Of course I have had to be brutally exposed (for lack of a better word) to the Google Maps API before I could do such things as make it work the first time. That said, I was not looking forward to trying to pull this information out of Google (we are so much smarter than you, and if don't believe it read our docs) docs.

over 1 year ago ·

Can you write this in full code? I still have no idea where to add them in a code provided by google.

over 1 year ago ·

This worked like a charm, you are the man. Thanks.

over 1 year ago ·