Android how to calculate optimal zoom level?

2019-05-22 14:55发布

问题:

How can I calculate the zoom level for the tracked route to fit perfectly to the view of map(screen)? I have the start and end point of root/whole track/ in Lon/Lat position, I able to calculate the zoom level with input parameter meter, but how many meters need I set? I would like to show the logged track on the map. I showed the track but doesn't fit into map.

回答1:

You can set the zoom with this code snippet, just need to pass the starting and ending geopoint in a list. If you have more than 2 points it also works.

private void fixZoom(MapController controller, List <GeoPoint> items){

    int minLat = Integer.MAX_VALUE;
    int maxLat = Integer.MIN_VALUE;
    int minLon = Integer.MAX_VALUE;
    int maxLon = Integer.MIN_VALUE;

    for (GeoPoint item : items) 
    { 

          int lat = item.getLatitudeE6();
          int lon = item.getLongitudeE6();

          maxLat = Math.max(lat, maxLat);
          minLat = Math.min(lat, minLat);
          maxLon = Math.max(lon, maxLon);
          minLon = Math.min(lon, minLon);
     }

    controller.zoomToSpan((int) (Math.abs(maxLat - minLat) * 1.1), (int)(Math.abs(maxLon - minLon) * 1.1)); //1.1 to have some padding on the edges.
    controller.animateTo(new GeoPoint( (maxLat + minLat)/2,(maxLon + minLon)/2 )); //so the center is positioned just in the middle

}

Hope that helps.