如何计算以多个标记为中心的缩放级别?

时间:2015-04-13 09:11:05

标签: android google-maps

我有一个以点为中心的地图,我在此地图中添加了几个标记,我需要在地图中显示所有标记,但我无法移动中心点。因此,我必须计算以点为中心的缩放级别,并显示我在此地图中添加的所有标记。

现在,我的解决方案是下一个代码,但我必须在for循环中移动相机,在某些情况下算法不能很好地工作。有没有办法更好地做这个算法???

private void calculateZoomLevel() {
    Marker marker = getFurthestPoint();

    if (marker != null) {
        boolean found = false;
        for (int i = (int) map.getMaxZoomLevel(); i >= map.getMinZoomLevel() && !found; i--) {
            map.moveCamera(CameraUpdateFactory.zoomTo(i));

            LatLngBounds boundaries = map.getProjection().getVisibleRegion().latLngBounds;
            if (boundaries.contains(marker.getPosition())) {
                found = true;
            }
        }
    }
}

private Marker getFurthestPoint() {
    float maxDistanceKm = 0;
    Marker furthestMarker = null;

    Iterator<Marker> it = clusterManager.getClusterMarkerCollection().getMarkers().iterator();
    while (it.hasNext()) {
        Marker marker = it.next();
        float distanceKm = calculateKilometers(marker.getPosition());
        if (maxDistanceKm < distanceKm) {
            maxDistanceKm = distanceKm;
            furthestMarker = marker;
        }
    }

    return furthestMarker;
}

private float calculateKilometers(LatLng positionPoi) {
    Location locationPoi = new Location("");
    locationPoi.setLatitude(positionPoi.latitude);
    locationPoi.setLongitude(positionPoi.longitude);

    Location locationUser = new Location("");
    locationUser.setLatitude(latitude);
    locationUser.setLongitude(longitude);

    return locationPoi.distanceTo(locationUser) / 1000;

}

1 个答案:

答案 0 :(得分:0)

private void calculateZoomLevel() {
    Marker marker = getFurthestPoint();

    double zoomLevel = 0;
    if (marker != null && latitude != 0 && longitude != 0) {
        float km = calculateKilometers(marker.getPosition());

        float dist = (GOOGLE_MAX_DISTANCE / km);
        zoomLevel = log(dist, 2);
    }
    moveZoom((float) zoomLevel);
}

private double log(double x, double base) {
    return (Math.log(x) / Math.log(base));
}

private Marker getFurthestPoint() {
    float maxDistanceKm = 0;
    Marker furthestMarker = null;

    Iterator<Marker> it = clusterManager.getClusterMarkerCollection().getMarkers().iterator();
    while (it.hasNext()) {
        Marker marker = it.next();
        float distanceKm = calculateKilometers(marker.getPosition());
        if (maxDistanceKm < distanceKm) {
            maxDistanceKm = distanceKm;
            furthestMarker = marker;
        }
    }

    return furthestMarker;
}

private float calculateKilometers(LatLng positionPoi) {
    Location locationPoi = new Location("");
    locationPoi.setLatitude(positionPoi.latitude);
    locationPoi.setLongitude(positionPoi.longitude);

    Location locationUser = new Location("");
    locationUser.setLatitude(latitude);
    locationUser.setLongitude(longitude);

    return locationPoi.distanceTo(locationUser) / 1000;

}