Google Maps: Auto Zoom & Centre Your MapAdd to My Brief

Vince Scordino | 14/10/2011

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.

Enjoy! 

tags: Web Development

Interested in learning more?

Wiliam is a leading supplier of web solutions and can provide expert advice to assist your business or organisation online.

Make enquiry   Request quotation

Comments

Share this page

Print this page Email this page to a friend Bookmark and Share

No Brief added yet.

My Brief results-driven approach emphasises a commitment to our clients needs through strategic analysis and best-practice.

Add to My Brief

Click on this icon to save item into My Brief. Retrieve, email and print

Drag & Drop

Drag & drop any iten with this icon into My Brief. Retrieve, email and print

Search Blogs