How do I find the center of multiple points? Andro

2019-05-09 23:56发布

问题:

I have multiple points placed on my MapView and would like to centre the map on these points i.e. not any particular one, just the averaged centre of the lot of them.

I know there's a method for this in the Javascript G. Maps API. I was wondering whether there was a prexisting method to do this in Android?

回答1:

this question looks suspiciously like one I had some time ago ...

Android MapView -setting zoom automatically until all ItemizedOverlay's are visible



回答2:

What you are trying to calculate is called a Centroid. There are several Java implementations for calculating centroids for a finite set of points (a polygon).

For example: JavaGeom has an implementation for finding the centroid of multiple 2D points.
I'm not sure if there's a standard android implementation for it, but it is fairly simple to implement yourself.

Simple implementation:

public static float[] centroid(float[] points) {
    float[] centroid = { 0, 0 };

    for (int i = 0; i < points.length; i+=2) {
        centroid[0] += points[i];
        centroid[1] += points[i+1];
    }

    int totalPoints = points.length/2;
    centroid[0] = centroid[0] / totalPoints;
    centroid[1] = centroid[1] / totalPoints;

    return centroid;
}


回答3:

You could take the average of the points x and y respectively, and then set the span based on these values and introduce a padding like 25% more than the value to insure that there is enough space to focus on it.

for more info check this out: http://code.google.com/android/add-ons/google-apis/reference/index.html



回答4:

I would not use the centroid (or barycenter, or centre of mass in case of uniform density), if you need to show a figure (a shapre, an area) in a layout. What I really need to center a figure in a layout, is the maximum and minimum of all the coordinates to show every point.

ArrayList<GeoPoint> track;

public GeoPoint CenterMap() {
    double longitude = 0;
    double latitude = 0;
    double maxlat = 0, minlat = 0, maxlon = 0, minlon = 0;
    int i = 0;
    for (GeoPoint p : track) {
        latitude = p.getLatitude();
        longitude = p.getLongitude();
        if (i == 0) {
            maxlat = latitude;
            minlat = latitude;
            maxlon = longitude;
            minlon = longitude;
        } else {
            if (maxlat < latitude)
                maxlat = latitude;
            if (minlat > latitude)
                minlat = latitude;
            if (maxlon < longitude)
                maxlon = longitude;
            if (minlon > longitude)
                minlon = longitude;
        }
        i++;
    }
    latitude = (maxlat + minlat) / 2;
    longitude = (maxlon + minlon) / 2;
    return new GeoPoint(latitude, longitude);
}


回答5:

Don't take the average of points x and y.. Google "centroid psuedocode" and that should be what you want.