如何在Google Maps Android API v2中计算多边形的中心?

use*_*455 6 android google-maps-android-api-2 android-maps-v2

我使用几个纬度,经度点在谷歌地图上绘制了一个多边形.但是现在我需要在多边形的中心放置一个标记,我需要中心坐标.如何计算中心点.

以下是在地图上添加多边形的代码:

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

        }
Run Code Online (Sandbox Code Playgroud)

我发现了类似的问题已经得到解答,但是对于JavaScript Api.Is他们在我的情况下使用相同的解决方案吗?

小智 24

我在下面的代码中找到多边形的中心点.它也为我工作

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;
    }
Run Code Online (Sandbox Code Playgroud)


use*_*455 11

下面是我现在用来找到多边形中心的代码: -

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;
    }
Run Code Online (Sandbox Code Playgroud)