此 Android 应用程序将用于帮助定义边界或城市限制等。用户将在 Google map 上绘制一个定义边界的矩形,应用程序将按预定义的量增加矩形的长度和宽度米。
我知道 API 中有一种方法可以计算坐标之间的距离,但在这里我从米开始,想要找到新的(要绘制的)较大多边形的坐标。有谁知道我将如何进行这个计算?提前致谢!
最佳答案
您可以使用 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);
关于java - 如何在 Google map 上绘制距用户输入点已定义距离(米)的多边形(矩形),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35977204/