【发布时间】:2021-07-31 08:59:50
【问题描述】:
我的谷歌地图上有一些区域被划分为多边形,我想要一些方法来识别某个点是否在多边形内。我刚刚尝试了识别多边形中的点的Ray Casting算法,但结果并不好。它不适用于非常不规则的多边形,在我的测试中实现是不可行的。
我将尝试做的事情留在这里。
光线投射功能:
bool rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ((aY > pY && bY > pY) || (aY < pY && bY < pY) || (aX < pX && bX < pX)) {
return false; // a and b can't both be above or below pt.y, and a or
// b must be east of pt.x
}
检查标记是否在多边形内的功能,光线投射的延续:
bool _checkIfValidMarker(LatLng tap, List<LatLng> vertices) {
int intersectCount = 0;
for (int j = 0; j < vertices.length - 1; j++) {
if (rayCastIntersect(tap, vertices[j], vertices[j + 1])) {
intersectCount++;
}
}
return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}
测试区域声明:
List<LatLng> _areaRed = [
LatLng(-20.54564560298607, -48.93099261363096),
LatLng(-20.47020914370705, -47.585960450443444),
LatLng(-20.888624642495724, -47.564486265123804),
LatLng(-21.275431646124073, -47.44904100868184),
LatLng(-21.53038557354785, -48.50412611872714)
];
List<LatLng> _areaBlue = [
LatLng(-20.583742560626508, -47.36628976946108),
LatLng(-19.732037376448474, -47.11388584796422),
LatLng(-20.091216049597158, -46.00876597546445),
LatLng(-20.70503248593602, -46.48287604422207),
LatLng(-21.297307144955976, -47.24008780871265)
];
List<LatLng> _areaGreen = [
LatLng(-20.588467827088945, -48.26017166238112),
LatLng(-18.32058633744915, -50.27657970099416),
LatLng(-17.474497720584548, -48.19666274777912),
LatLng(-17.988676302476964, -46.25964085241858),
LatLng(-18.877360628508573, -46.9899933703414)
];
调用函数检查某个区域内的点。 _currentLocation.latitude 指的是 GPS 获取的位置,不过我也用固定坐标测试过。
insideArea = _checkIfValidMarker(LatLng(_currentLocation.latitude, _currentLocation.longitude),
_areaGreen);
【问题讨论】:
-
您可以尝试使用google_map_polyutil 包。它有一个方法“containsLocation”计算给定点是否位于指定多边形内
-
我考虑过这种可能性,但考虑到我的其他包包,这个包已经过时了
标签: flutter google-maps dart