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

标签 java android google-maps-android-api-2

我的坐标来自数据库

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

要求的结果:

enter image description here

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

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

得到的结果:

enter image description here

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

关于java - 给定两个点坐标计算矩形坐标android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49434888/

相关文章:

php - android相当于PHP的函数explode()

java - 使用 Glide Image Load setDataSource 运行时异常失败 : status =

android - Google Maps v2 上的动画透明圆圈动画不正确

java - 如果出现其他错误我不明白这个错误

java - java中的正则表达式删除=之前和之后的空格

android - Sqlite 数据库在 Samsung Android Oreo 8.0 设备中无法正常运行

安卓谷歌地图只有一个国家

android - 为 Google Map v2 fragment 创建 OnDragListener

java - 使用 log4j2 和 slf4j : java. lang.StackOverflowError

java - 将 *.jar 导入 Maven 项目时遇到问题