为两个LatLong值计算Google Map的缩放级别

时间:2013-09-06 16:57:40

标签: android google-maps

我在com.google.android.gms.maps.GoogleMap中使用SherlockFragmentActivity

XML代码是这样的:

            <fragment
                android:id="@+id/map"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:layout_width="fill_parent"
                android:layout_height="150dip" />

int zoomLevel =? //我如何计算两个不同latlong值的缩放级别 因为android map v3需要将缩放级别告诉为int

map.setZoom(zoomLevel);

我的起始值和目标值为com.google.android.gms.maps.model.LatLng

LatLng开始,结束;

我正在添加像GoogleLocation.addPolyLineOnGMap(mMap, startPoint, endPoint, startMarker, endMarker)

这样的pligon

我的问题是如何计算Google地图的缩放级别,以便它可以在地图上正确显示两个标记。

3 个答案:

答案 0 :(得分:14)

使用LatLngBounds.Builder添加其中的所有边界并构建它,然后创建CameraUpdate对象并使用填充传递updatefactory中的边界。使用此CameraUpdate对象为地图相机设置动画。

LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (Marker m : markers) {
            builder.include(m.getPosition());
        }
        LatLngBounds bounds = builder.build();
        int padding = ((width * 10) / 100); // offset from edges of the map
                                            // in pixels
        CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                padding);
        mMap.animateCamera(cu);

答案 1 :(得分:2)

对我来说,我需要按GoogleMapOptions计算初始地图设置的缩放比例,因此使用LatLngBounds.Builder 不会工作,也不会优化。这就是我根据城市的东北和西南坐标计算缩放的方法

它引用了herethis answer,你可以简单地将下面的代码放到你的助手类中:

final static int GLOBE_WIDTH = 256; // a constant in Google's map projection
final static int ZOOM_MAX = 21;

public static int getBoundsZoomLevel(LatLng northeast,LatLng southwest,
                                     int width, int height) {
    double latFraction = (latRad(northeast.latitude) - latRad(southwest.latitude)) / Math.PI;
    double lngDiff = northeast.longitude - southwest.longitude;
    double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
    double latZoom = zoom(height, GLOBE_WIDTH, latFraction);
    double lngZoom = zoom(width, GLOBE_WIDTH, lngFraction);
    double zoom = Math.min(Math.min(latZoom, lngZoom),ZOOM_MAX);
    return (int)(zoom);
}
private static 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 static double zoom(double mapPx, double worldPx, double fraction) {
    final double LN2 = .693147180559945309417;
    return (Math.log(mapPx / worldPx / fraction) / LN2);
}

仅通过LatLng

创建new LatLng(lat-double, lng-double)

widthheight是地图布局大小(以像素为单位)

答案 2 :(得分:0)

在Android中:

LatLngBounds group = new LatLngBounds.Builder()
                .include(tokio)   // LatLgn object1
                .include(sydney)  // LatLgn object2
                .build();

mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(group, 100)); // Set Padding and that's all!
相关问题