在使用map.fitBounds之前,如何确定LatLngBounds的缩放级别? [英] How do I determine the zoom level of a LatLngBounds before using map.fitBounds?
问题描述
我试图在调用map.fitBounds()之前找出一种确定Map缩放级别的方法,并且我似乎找不到方法。
I am trying to figure out a way of determining the zoom level of a Map before I call map.fitBounds(), and I cannot seem to find a way.
在API v2中,有一种方法 GMap.getBoundsZoomLevel(bounds:GLatLngBounds)
,但我无法在API v3文档中找到等价物。
In the API v2 there was a method GMap.getBoundsZoomLevel(bounds:GLatLngBounds)
, but I can't find an equivalent in the API v3 documentation.
是否有一个非Google algorythm用于确定事先的缩放级别?
Is there a non-Google algorythm for determining what a zoom level will be beforehand?
推荐答案
Nick是对的,这个讨论概述了一个可行的方法:
谷歌地图V3 - 如何计算给定边界的缩放级别
Nick is right, this discussion outlines a workable method: Google Maps V3 - How to calculate the zoom level for a given bounds
但是,它在Javascript中。对于那些需要使用Android GMaps v3的人来说,以下是翻译:
However, it is in Javascript. For those needing to do this with Android GMaps v3, the following is a translation:
private static final double LN2 = 0.6931471805599453;
private static final int WORLD_PX_HEIGHT = 256;
private static final int WORLD_PX_WIDTH = 256;
private static final int ZOOM_MAX = 21;
public int getBoundsZoomLevel(LatLngBounds bounds, int mapWidthPx, int mapHeightPx){
LatLng ne = bounds.northeast;
LatLng sw = bounds.southwest;
double latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / Math.PI;
double lngDiff = ne.longitude - sw.longitude;
double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
double latZoom = zoom(mapHeightPx, WORLD_PX_HEIGHT, latFraction);
double lngZoom = zoom(mapWidthPx, WORLD_PX_WIDTH, lngFraction);
int result = Math.min((int)latZoom, (int)lngZoom);
return Math.min(result, ZOOM_MAX);
}
private double latRad(double lat) {
double sin = Math.sin(lat * Math.PI / 180);
double radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
private double zoom(int mapPx, int worldPx, double fraction) {
return Math.floor(Math.log(mapPx / worldPx / fraction) / LN2);
}
这篇关于在使用map.fitBounds之前,如何确定LatLngBounds的缩放级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!