给定两个点坐标计算矩形坐标android

Given two point coordinates calculate rectangle coordinates android

我的坐标来自数据库

 (x,y) ->   (37.18312184219552, -122.5216064453125), (37.74655686277364, -122.63720703125).

我需要找到等效的矩形边界以传递给此函数。

Polygon polygon = map.addPolygon(new PolygonOptions()
        .add(new LatLng(0, 0), new LatLng(0, 5), new LatLng(3, 5), new LatLng(0, 0))
        .strokeColor(Color.RED)
        .fillColor(Color.BLUE));

要求的结果:

当我这样做时,它显示两条线而不是矩形。

points.add(new LatLong(x,y)); <-- x and y passed from given coordinates
googleMap.addPolygon(new PolygonOptions()
                                .addAll(points)
                                .strokeColor(Color.RED)
                                .fillColor(Color.BLUE));

获得的结果:

JS有计算矩形边界的函数,但是Google Maps Android API好像没有函数和方法。谁能帮我解决这个问题。

可能是因为您只向多边形添加了 2 个点?如果是这样,那么这 2 个点标记所需矩形的对角线 - 您需要矩形的其他 2 个角。下面的代码将创建矩形缺少的 2 个点并绘制矩形:

public static Polygon drawRectangle(Context context,
                                    GoogleMap googleMap,
                                    LatLng latLng1,
                                    LatLng latLng2,
                                    int strokeWidth,
                                    int strokeColor,
                                    int fillColor) {
    Polygon polygon = null;

    if (context != null && googleMap != null && latLng1 != null && latLng2 != null) {
        // create the other 2 points of the rectangle
        LatLng latLng3 = new LatLng(latLng1.latitude, latLng2.longitude);
        LatLng latLng4 = new LatLng(latLng2.latitude, latLng1.longitude);

        googleMap.addPolygon(new PolygonOptions()
                .add(latLng1)
                .add(latLng3)
                .add(latLng2)
                .add(latLng4)
                .strokeWidth(strokeWidth)
                .strokeColor(strokeColor)
                .fillColor(fillColor));
    }

    return polygon;
}

你这样称呼它:

    Polygon polygon = drawRectangle(context,googleMap,
            latLng,marker.getPosition(),
            8,Color.BLACK,Color.parseColor("#44444444"));