6
votes

I have an API that returns an array of latitudes and longitudes that define the boundaries of an area on a map(polygon).

an example of a polygon

In my react-native app, I have react-native-maps installed. How do I check if the user's location is in the polygon returned by the api?

I know this can be achieved with google maps web with the containsLocation() function. Does a function like that exist for react-native-maps?

4

4 Answers

5
votes

react-native-maps doesn't expose that function, but there are two packages that I'm aware of that can help you:

  1. react-native-geo-fencing that does the same as the google maps utility you've mentioned.

  2. react-native-geo-fence handles location checks for you and exposes events you can hook into.

5
votes

For anyone still looking for an easier alternative (or for Circle support just like I needed it), look into using geolib: https://github.com/manuelbieh/Geolib.

Installation is simple and straightforward:

$yarn add geolib

Afterward in your React Native project, import it using:

import geolib from 'geolib'

And then just use the API as explained in the README.md.

0
votes

geolibe is the best solution. react-native-geo-fencing is deprecated and it cause more errors to your project and also react-native-geo-fence is not what you want

0
votes

My code to check if lat, lon is inside object of many polys. It returns true if coordinate is inside one of the polygons.

 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;

};