6

在调用 map.fitBounds() 之前,我试图找出一种确定地图缩放级别的方法,但我似乎找不到方法。

在 API v2 中有一个方法GMap.getBoundsZoomLevel(bounds:GLatLngBounds),但我在 API v3 文档中找不到等价物。

是否有非谷歌算法来预先确定缩放级别?

4

1 回答 1

14

尼克是对的,这个讨论概述了一种可行的方法: Google Maps V3 - How to calculate the zoom level for a given bounds

但是,它是在 Javascript 中的。对于那些需要使用 Android GMaps v3 执行此操作的人,以下是翻译:

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);
}
于 2014-05-04T23:39:31.067 回答