androidgoogle-maps-android-api-2android-maps-v2

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


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?


Solution

  • Below is the code which I am using now to find the center of polygon:-

    public static double[] centroid(List<PolyPoints> 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 centroid;
        }