javascript 等效于 gmaps api 3 中的 getBoundsZoomLevel()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9837017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:58:57  来源:igfitidea点击:

Equivalent of getBoundsZoomLevel() in gmaps api 3

javascriptgoogle-mapsgoogle-maps-api-3google-maps-api-2

提问by TMS

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.

在 API v2 中,地图对象有一个方便的方法getBoundsZoomLevel()。我用它来获得最适合边界的缩放级别,然后以某种方式操纵这个最佳缩放级别,最后设置所需的缩放级别。

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

我在API v3 中找不到类似的功能。(从 v2 迁移到 v3 时的持续令人沮丧的体验)

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

我真的必须再次使用map.fitBounds(), map.getZoom(), 操作setZoom()吗?真是太蠢了!

回答by Engineer

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