Equivalent of getBoundsZoomLevel() in gmaps api 3

TMS picture TMS · Mar 23, 2012 · Viewed 14.3k times · Source

In API v2, the map object had a handy method getBoundsZoomLevel(). I used it to get the zoom level which fits the bounds best, then manipulated this optimal zoom level somehow and finally set the desired zoom level.

I cannot find similar function in API v3. (What a continuous frustrating experience when moving from v2 to v3)

Do I really have to use map.fitBounds(), map.getZoom(), manipulate and setZoom() again? That's really stupid!

Answer

Engineer picture Engineer · Apr 2, 2012

Below is a function I have implemented:

/**
* Returns the zoom level at which the given rectangular region fits in the map view. 
* The zoom level is computed for the currently selected map type. 
* @param {google.maps.Map} map
* @param {google.maps.LatLngBounds} bounds 
* @return {Number} zoom level
**/
function getZoomByBounds( map, bounds ){
  var MAX_ZOOM = map.mapTypes.get( map.getMapTypeId() ).maxZoom || 21 ;
  var MIN_ZOOM = map.mapTypes.get( map.getMapTypeId() ).minZoom || 0 ;

  var ne= map.getProjection().fromLatLngToPoint( bounds.getNorthEast() );
  var sw= map.getProjection().fromLatLngToPoint( bounds.getSouthWest() ); 

  var worldCoordWidth = Math.abs(ne.x-sw.x);
  var worldCoordHeight = Math.abs(ne.y-sw.y);

  //Fit padding in pixels 
  var FIT_PAD = 40;

  for( var zoom = MAX_ZOOM; zoom >= MIN_ZOOM; --zoom ){ 
      if( worldCoordWidth*(1<<zoom)+2*FIT_PAD < $(map.getDiv()).width() && 
          worldCoordHeight*(1<<zoom)+2*FIT_PAD < $(map.getDiv()).height() )
          return zoom;
  }
  return 0;
}