Sometimes in the given set of latitudinal and longitudinal coordinates you want to just automatically zoom or center for your map. This is achievable using Google Maps JavaScript API 3.2 with the following code. The code assumes you can loop through your set of latlng values to discover the minimum and maximum of both values.

(Autoscaling Google Maps with multiple markers.)

I just want this tutorial to be focused on autoscaling so I’m not writing how to display the markers like the screenshot above. There’re many articles and demos covering that subject much better than I can. If you just like to see the full set of codes, just scroll to the bottom of the article.

1. Creating the Google Maps object

First, we’ll need to create the Google Maps object which initialize Google Maps on your webpage. I have a div element with the id “panel_maps” which I intend to use for this tutorial. This would initialize Google Maps as an object but I haven’t specify the centering and zooming parameters yet:

[code lang=“javascript”]var map = new google.maps.Map(

document.getElementById(“panel_maps”),

{mapTypeId: google.maps.MapTypeId.ROADMAP}

);[/code]

2. The minimum and maximum of latitude and longitude

I’m skipping this step to get the min and max of the latitude and longitude since the method is largely dependent on how you iterate through your data structure. I will use the following values for the minimum and maximum:

[code lang=“javascript”]//Example values of min & max latlng values

var lat_min = 1.3049337;

var lat_max = 1.3053515;

var lng_min = 103.2103116;

var lng_max = 103.8400188;[/code]

3. Setting the center point of the map

To set the center, you have to find the midpoint between the min and max latitude as well as the min and max longitude:

[code lang=“javascript”]map.setCenter(new google.maps.LatLng(

((lat_max + lat_min) / 2.0),

((lng_max + lng_min) / 2.0)

));[/code]

4. Setting the zoom for the map

To set the zoom, you can use LatLngBounds to define a boundary where the points can be fit into map:

[code lang=“javascript”]map.fitBounds(new google.maps.LatLngBounds(

//bottom left

new google.maps.LatLng(lat_min, lng_min),

//top right

new google.maps.LatLng(lat_max, lng_max)

));[/code]

And that’s all.

The full code

So here’s how the full code look like:

[code lang=“javascript”]var map = new google.maps.Map(

document.getElementById(“panel_maps”),

{mapTypeId: google.maps.MapTypeId.ROADMAP}

);

//Example values of min & max latlng values

var lat_min = 1.3049337;

var lat_max = 1.3053515;

var lng_min = 103.2103116;

var lng_max = 103.8400188;

map.setCenter(new google.maps.LatLng(

((lat_max + lat_min) / 2.0),

((lng_max + lng_min) / 2.0)

));

map.fitBounds(new google.maps.LatLngBounds(

//bottom left

new google.maps.LatLng(lat_min, lng_min),

//top right

new google.maps.LatLng(lat_max, lng_max)

));[/code]

Have fun with the API, hope it works for you as it did for me.

comments powered by Disqus