如何在Google地图上绘制多边形(矩形),并在用户的输入点

时间:2016-03-13 23:27:41

标签: java android google-maps

此Android应用程序将用于帮助定义边框或城市限制等。用户将在Google地图上绘制一个定义边框的矩形,应用程序将按预定义的数量增加矩形的长度和宽度米。

我知道API中有一种方法可以计算坐标之间的距离,但是这里我从米开始,想要找到新的(要绘制的)更大的多边形的坐标。有谁知道我怎么做这个计算?提前致谢!

2 个答案:

答案 0 :(得分:0)

在获取多边形的坐标时,您可以检查codepen如何执行此操作。此处的输出将是坐标集(Lat和Lng)。由于您希望以米为单位获得坐标,因此可以使用spherical geometry来计算距离。

要计算此距离,请调用computeDistanceBetween(),将两个LatLng对象传递给它。  距离结果以米为单位。

查看此SO问题以获取更多信息。

SO ticket 7997627

SO ticket 5072059

答案 1 :(得分:0)

您可以使用Google Maps Android API Utility Library

中的SphericalUtil.computeOffset方法
// The distance you want to increase your square (in meters)
double distance = 104.52;

// A List of LatLng defining your user's input
// (Two latLng define a square)
List<LatLng> positions = new ArrayList<>();
positions.add(new LatLng(40.22861, -3.95567));
positions.add(new LatLng(40.22884, -3.95342));

// Create a LatLngBounds.Builder and include your positions
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng position : positions) {
    builder.include(position);
}

// Calculate the bounds of the initial positions
LatLngBounds initialBounds = builder.build();

// Increase the bounds by the given distance
// Notice the distance * Math.sqrt(2) to increase the bounds in the directions of northeast and southwest (45 and 225 degrees respectively)
LatLng targetNorteast = SphericalUtil.computeOffset(initialBounds.northeast, distance * Math.sqrt(2), 45);
LatLng targetSouthwest = SphericalUtil.computeOffset(initialBounds.southwest, distance * Math.sqrt(2), 225);

// Add the new positions to the bounds
builder.include(targetNorteast);
builder.include(targetSouthwest);

// Calculate the bounds of the final positions
LatLngBounds finalBounds = builder.build();

您可以使用以下函数绘制边界以查看是否一切正常:

private void drawBounds (LatLngBounds bounds, int color) {
    PolygonOptions polygonOptions =  new PolygonOptions()
            .add(new LatLng(bounds.northeast.latitude, bounds.northeast.longitude))
            .add(new LatLng(bounds.southwest.latitude, bounds.northeast.longitude))
            .add(new LatLng(bounds.southwest.latitude, bounds.southwest.longitude))
            .add(new LatLng(bounds.northeast.latitude, bounds.southwest.longitude))
            .strokeColor(color);

    mMap.addPolygon(polygonOptions);
}

例如:

drawBounds (initialBounds, Color.BLUE);
drawBounds (finalBounds, Color.RED);