3

I have a set of GeoPoints and want to find the Lat/Lon center and and spans that include all these GeoPoints (so they're visible all on the MapView).

On a planar map this would be rather simple, find the highest and lowest x/y values, find the center by adding half of the absolute distance to the lower value.

But how is this done for the spherical world map, where the max/min values of -180/+180 and +90/-90 are next to each other?

Here's what I'm trying to do:

public void zoomToGeoPoints(GeoPoint... geoPoint) {

    MapController mc = getController();
    if (geoPoint == null) {
        Log.w(TAG, "No geopoints passed, doing nothing!");
        return;
    }

    // Set inverse max/min start values 
    int maxLat = (int) (-90 * 1E6);
    int maxLon = (int) (-180 * 1E6);
    int minLat = (int) (90 * 1E6);
    int minLon = (int) (180 * 1E6);

    // Find the max/min values
    for (GeoPoint gp : geoPoint) {
        maxLat = Math.max(maxLat, gp.getLatitudeE6());
        maxLon = Math.max(maxLon, gp.getLongitudeE6());
        minLat = Math.min(minLat, gp.getLatitudeE6());
        minLon = Math.min(minLon, gp.getLongitudeE6());
    }

    // Find the spans and center point
    double spanLat = Math.abs(maxLat - minLat);
    double spanLon = Math.abs(maxLon - minLon);

    int centerLat = (int) ((minLat + spanLat / 2d));
    int centerLon = (int) ((minLon + spanLon / 2d));

    GeoPoint center = new GeoPoint(centerLat, centerLon);

    // Pan to center
    mc.animateTo(center);           

    // Zoom to include all GeoPoints
    mc.zoomToSpan((int)(spanLat), (int)(spanLon));
Bachi
  • 6,408
  • 4
  • 32
  • 30
  • Very similar to questions [Google MAP API v3: Center & Zoom on displayed markers](http://stackoverflow.com/questions/2818984/google-map-api-v3-center-zoom-on-displayed-markers), and the rather less informative [google map zoom to fit](http://stackoverflow.com/questions/11309914/google-map-zoom-to-fit). – Jim DeLaHunt Nov 14 '12 at 08:24

1 Answers1

0

Untested, using the Maps API in JavaScript to calculate the desired smallest bounding box:

// points[] is your array of geo points
var boundbox = new map.LatLngBounds();
for (var i=0; i<points.length; i++){ 
  boundbox.extend(points[i]);
}
var center = boundbox.getCenter();
Jpsy
  • 20,077
  • 7
  • 118
  • 115
  • I would assume the LatLngBounds() helper in the Maps API V2 would do the trick. As API v2 is by now the default, I'll mark this as the answer. – Bachi Jun 30 '13 at 17:09