Google Maps v3 getBoundsZoomLevel - Using projection

by john_s

HTML

<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;dummy=.js"></script>
<div id="mapDiv" style="width: 500px; height: 375px; border: solid 2px #666;">
</div>

JavaScript

// Change this array to test.
var points = [
    { lat: 36.170603, lng: -179 },
    { lat: 35.144478, lng: 179 }
];

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 = (ne.x > sw.x) ? (ne.x - sw.x) : (ne.x - sw.x + 256);
  var worldCoordHeight = (sw.y - ne.y);

  //Fit padding in pixels 
  var FIT_PAD = 0;

  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;
} 

function getBoundsZoomLevel(map, bounds){

    function zoom(mapPx, zoom0Px) {
        return Math.floor(Math.log(mapPx / zoom0Px) / Math.LN2);
    }

    var $mapDiv = $(map.getDiv());
        mapType = map.mapTypes.get(map.getMapTypeId()),
        projection = map.getProjection();

    var mapDim = { height: $mapDiv.height(), width: $mapDiv.width() };

    var maxZoom = mapType.maxZoom || 21;
    var minZoom = mapType.minZoom || 0;

    var nePoint = projection.fromLatLngToPoint(bounds.getNorthEast());
    var swPoint = projection.fromLatLngToPoint(bounds.getSouthWest()); 

    var zoom0Width = (nePoint.x > swPoint.x)
        ? (nePoint.x - swPoint.x)
        : (nePoint.x - swPoint.x + 256);
    var zoom0Height = swPoint.y - nePoint.y;
    
    console.log('nePoint.x=' + nePoint.x);
    console.log('swPoint.x=' + swPoint.x);
    console.log('zoom0Width=' + zoom0Width);
    console.log('zoom0Height=' + zoom0Height);
    
    var latZoom = zoom(mapDim.height, zoom0Height);
    var lngZoom = zoom(mapDim.width, zoom0Width);

    return Math.min(latZoom, lngZoom, maxZoom);
}

function createMarkerForPoint(point)...