How do I calculate the center of a polygon in Google Maps Android API v2?

user818455 picture user818455 · Aug 26, 2013 · Viewed 14.3k times · Source

I have drawn a polygon on google map using several Latitude,Longitude points.But now I need to place a marker at the center of the polygon for which I need the center coordinates.How do I calculate the center point.

Below is the code for adding polygons on map:

for (Warning w : warningsList) {
            // Instantiates a new Polygon object and adds points
            PolygonOptions rectOptions = new PolygonOptions();
            List<PolyPoints> pp = w.getPolyPoints();
            for (PolyPoints p : pp) {
                rectOptions.add(new LatLng(Double.valueOf(p.getLatitude()),
                        Double.valueOf(p.getLongitude())));
            }

                mMap.addPolygon(rectOptions.strokeColor(Color.GREEN)
                        .fillColor(Color.RED).strokeWidth(STROKE_WIDTH));

        }

I found similar question which has been answered but thats for JavaScript Api.Is their any way of using the same solution in my case?

Answer

Thinesh picture Thinesh · Dec 22, 2014

Below code I am using to find the center point of the polygon. its working for me too

private LatLng getPolygonCenterPoint(ArrayList<LatLng> polygonPointsList){
        LatLng centerLatLng = null;
        Builder builder = new LatLngBounds.Builder(); 
        for(int i = 0 ; i < polygonPointsList.size() ; i++) 
        {          
            builder.include(polygonPointsList.get(i));
        }
        LatLngBounds bounds = builder.build();
        centerLatLng =  bounds.getCenter();

        return centerLatLng;
    }