Equivalent of getBoundsZoomLevel() in gmaps api 3 [duplicate]

☆樱花仙子☆ 提交于 2019-11-28 22:34:38

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/9837017/equivalent-of-getboundszoomlevel-in-gmaps-api-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!