hojgtq
Last Updated: June 02, 2017
·
35.28K
· neutralino1
981494 10151466984546915 1613396205 o

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.lat(), marker.position.lng());
bounds.extend(loc);

After all markers have been added:

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

That's it, cheers.

Say Thanks
Respond

4 Responses
Add your response

12514
0d38ee92831618c24839dc002859c32f

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

over 1 year ago ·
27916

Hi,
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 ·
28185

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 ·
29000

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

6 months ago ·