Quantcast
Viewing latest article 8
Browse Latest Browse All 9

How to auto zoom and auto center Google Maps

This post discusses how to auto center and auto zoom a Google Map to display all of the markers optimally.

In order to get accomplish this, you have to calculate the center point and zoom level manually via code. Fortunately this is pretty easy to do, you just need to calculate the minimum and maximum latitude/longitude of all of your markers and then get the center point of the resulting area (which will be a rectangle).

I’m using the Google Maps for ASP.NET control by Subgurim, but this method should apply to any other control, and should even work with plain JavaScript.

Auto center

First, you will need to find out the min/max latitude and longitude for your markers, this can usually be done in one pass at the same time as you add them. Here’s some Visual Basic.NET code to help you out (I’m using VB.NET for this project at the request of my collaborator, but it should be easy to convert to C# – think of it as pseudo code):

You then just need to calculate the center point of the resulting area. This is as easy as:

You can now center your map widget to these coordinates.

Auto zoom

The auto zoom part is where it gets a little tricky. In my application I’m calculating the distance in miles from the minLatitude, minLongitude coordinate to the maxLatitude, maxLongitude coordinate.

The formula for calculating the distance in miles between two coordinates is:


        miles = (3958.75 * Math.Acos(Math.Sin(latitude1 / 57.2958) * Math.Sin(latitude2 / 57.2958) + Math.Cos(latitude1 / 57.2958) * Math.Cos(latitude2 / 57.2958) * Math.Cos(longitude2 / 57.2958 - longitude1 / 57.2958)))

By calculating how many miles your markers span, you can make an informed guess on which zoom level to use. For instance, if the distance between the furthest two markers is less than 0.2 miles, then you could use the maximum zoom level available—which is 16 by the way—; if the distance is more than 0.2 miles and less than 0.5 miles—use zoom level 15, and so on.

Here’s a list of zoom levels for distances up to 15 miles:

That’s it, your map should now be able to auto zoom and auto center itself on your markers!

[tags]Google Maps API, Visual Basic.NET[/tags]

Image may be NSFW.
Clik here to view.

Viewing latest article 8
Browse Latest Browse All 9

Trending Articles