How do I find the center of multiple points? Android

谁说胖子不能爱 提交于 2019-12-06 01:29:16
Someone Somewhere

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

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

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;
}

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

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);
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!