在react-native-maps中检查点是否存在于多边形内?

9
我有一个API,它返回一个包含纬度和经度的数组,用于定义地图上区域(多边形)的边界。

an example of a polygon

在我的React Native应用中,我已经安装了react-native-maps。如何检查用户的位置是否在API返回的多边形内?
我知道可以使用Google Maps Web的containsLocation()函数实现此目的。是否存在类似于react-native-maps的函数?
4个回答

9

如果您还在寻找更简便的替代方案(或者像我一样需要支持 Circle 的支持),请考虑使用 geolib https://github.com/manuelbieh/Geolib

安装过程非常简单:

$yarn add geolib

然后,在您的 React Native 项目中导入它:

import geolib from 'geolib'

接下来,只需按照 README.md 中的说明使用 API 即可。


我在安卓中遇到了这个错误:ERROR TypeError: Cannot read property isPointInPolygon of undefined, js engine: hermes - Tinkaal Gogoi

5

react-native-maps并没有暴露该功能,但是我知道有两个包可以帮助你:

  1. react-native-geo-fencing可以执行与你提到的Google Maps实用程序相同的操作。

  2. react-native-geo-fence可以为你处理位置检查,并公开你可以连接到的事件。


两个选项都已经相当老了。就像@ItWillDo在下面提到的那样,geolib是最好的替代方案,提供了isPointInPolygon(point, polygon)函数。 - delkant

1

geolibe 是最佳解决方案。 react-native-geo-fencing 已经过时,会给您的项目带来更多错误, 而react-native-geo-fence 不是您想要的。


0

我的代码用于检查经纬度是否在多边形对象内部。如果坐标在其中一个多边形内部,则返回true。

 isInsidePoly = (lat, lon, multiPolycoords) => {
// ray-casting algorithm based on
// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html/pnpoly.html

var x = lat,
  y = lon;

var inside = false;
multiPolycoords.map(poly => {
  vs = poly;
  for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    var xi = vs[i].latitude,
      yi = vs[i].longitude;
    var xj = vs[j].latitude,
      yj = vs[j].longitude;

    var intersect =
      yi > y != yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
    if (intersect) inside = !inside;
  }
});

return inside;

};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接