Search code examples
google-maps-api-3google-geocoder

Automatically Finding Appropriate Zoom for Geocoding Result


I'm using Google Maps and Google Geocoding service for my location service application. I use Google Geocoding service for translating address to lat/lng position. My problem is how to automatically find an appropriate zoom for a certain address like the maps.google.com does.

For example, when I search a street in maps.google.com (e.g. Cisitu Baru, Bandung), it will show the street in smaller zoom. When I search a region (e.g. Bandung), it will show larger zoom. And a larger zoom for province (e.g. Jawa Barat / West Java), and so on.

I have tried both

var geocoder = new google.maps.Geocoder();
geocoder.geocode( {
    'address': someAddress
}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        console.dir(results);
        //cut
        map.panToBounds(results[0].geometry.bounds); //setting bound
        //cut
    }
});

and

//cut
map.panToBounds(results[0].geometry.viewports); //setting bound
//cut

(Honestly, I still don't know what's the difference between bounds and viewport and what are their uses from code.google.com/apis/maps/documentation/javascript/geocoding.html)

but both still don't display the map in appropriate zoom.

Right now, I use a small hack like this

var tabZoom =  {
    street_address: 15,
    route: 15,
    sublocality: 14,
    locality: 13,
    country: 10
};
//cut
map.setCenter(results[0].geometry.location);
if (tabZoom[results[0].types[0]] != undefined){
    map.setZoom(tabZoom[results[0].types[0]]);
} else {
    map.zetZoom(10);
}
//cut

Is there other solution? (Or anything from Google Map API that I don't know yet?)

Thanks!


Solution

  • use GLatLngBounds class

    an example:

    // map: an instance of GMap2
    
    // latlng: an array of instances of GLatLng
    
    var latlngbounds = new GLatLngBounds( );
    
    for ( var i = 0; i < latlng.length; i++ )
    {
        latlngbounds.extend( latlng[ i ] );
    }
    
    map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );
    

    ^

    The trick is to add the list of all points that need to be visible on the map simultaneously into a GLatLngBounds object. The Google Maps API can do the rest of the maths.

    or in v3 you can use LatLngBounds class (similar to GLatLngBounds in v2), link: http://code.google.com/apis/maps/documentation/javascript/reference.html#LatLngBounds

    for an example better check this out: http://unicornless.com/code/google-maps-v3-auto-zoom-and-auto-center