Google Maps: Auto Zoom & Centre Your Map
One of my favourite tasks as a web developer is working with the Google Maps API. On a recent project, I was assigned the duty of developing an events component whereby a range of upcoming events were presented to the user, as well as being plotted on a Google map.
Let’s skip ahead a few hours and assume we have our points plotted on our map. Upon recently, I have centred my map by hard-coding longitude/latitude values (-26.8241, 133.7751) and a zoom level (4):
map.setCenter(new GLatLng(-26.8241, 133.7751), 4)
This method has worked for me in the past only because I was showing events based on a state (centre on NSW and zoom to level 4)
After a short time Googling, I found that I could get the Google API to dynamically find the centre of my map based on my results, as well as diplaying these at a suitable zoom level:
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
To do this, we create a GLatLngBounds() object after we’ve created our map:
var bounds = new GLatLngBounds();
We then create our point(s) as usual (this generally in the form of looping an array):
//replace Latitude & Longitude with values
var point = new GLatLng(Latitude, Longitude);
//create marker
var marker = new GMarker(point);
//extend bounds to include this point
bounds.extend(point);
//add marker to map
map.addOverlay(marker);
We then call the setCenter() method with the following parameters:
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
Using the method bound.getCenter() will get you the centre of the map results, whilst map.getBoundsZoomLevel() will get you the best zoom level to fit all results.