Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

javascript - How do I determine the zoom level of a LatLngBounds before using map.fitBounds?

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.

In the API v2 there was a method GMap.getBoundsZoomLevel(bounds:GLatLngBounds), but I can't find an equivalent in the API v3 documentation.

Is there a non-Google algorythm for determining what a zoom level will be beforehand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nick is right, this discussion outlines a workable method: Google Maps V3 - How to calculate the zoom level for a given bounds

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...