java - 如何在 Google map 上绘制距用户输入点已定义距离(米)的多边形(矩形)

标签 java android google-maps

此 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/

相关文章:

ios - 无法识别的选择器发送到实例.. MapView 委托(delegate)的 'NSInvalidArgumentException'

android - 以编程方式检测调试 keystore 或发布 keystore

java - 如何将变量递增到字母表中的下一个或上一个字母?

java - "Accidental override: The following declarations have the same JVM signature"实现Java接口(interface)时

android - 如何在 Espresso 中测试 Android 通知

java - Java 中自己的事件无法修改类对象?

jquery - Google map 多边形渲染不正确

java - 用 Java 编写台球游戏 - 如何定义球并移动它们(通过 Graphics g)?

java - 如何更改j2me netbeans 6.9模拟器

java - 条件编译: Getting and testing the package name at compile time