Sunday 8 February 2015

Android calculate the center of Polygon in GoogleMap | Show centroid of polygon on map

Hello Friends,
           Today, I am sharing my code which helps you in calculating Centroid of a polygone
and show it on Google Map.



public static LatLng getCentroid(ArrayList<IGeoPoint> points) {
        double[] centroid = { 0.0, 0.0 };
        for (int i = 0; i < points.size(); i++) {
            centroid[0] += points.get(i).getLatitude();
            centroid[1] += points.get(i).getLongitude();
        }
        int totalPoints = points.size();
        centroid[0] = centroid[0] / totalPoints;
        centroid[1] = centroid[1] / totalPoints;

        return new LatLng(centroid[0], centroid[1]);
}


Hope, Its helps someone.
Enjoy Coding.... :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

2 comments:

  1. Hi, what type of object is polypoints??
    I ask you that because it don't work with my polygon. That's my code:

    poligonoOptions = new PolygonOptions()
    .add(new LatLng(37.379749, -6.007010))
    .add(new LatLng(37.381335, -6.008748))
    .add(new LatLng(37.382170, -6.007579))
    .add(new LatLng(37.380619, -6.005868))
    .add(new LatLng(37.379749, -6.007010));

    ReplyDelete
  2. Hello Alejandro,
    I just update the code , its "IGeoPoint" not ploypoints.
    And its contain the latitude and longitude.

    ReplyDelete

 

Copyright @ 2013 Android Developers Blog.