How to check if a custom location is inside polygon in react native expo

I have a react native project using Expo. I have used react native maps to show map with a polygon to show a city. I have autocomplete dropdown. Now I want to check if selected address is inside the polygon or no.

I have tried node modules like react-native-geo-fencing & react-native-contains-location but both doesn’t work with expo as they are react-native modules.

I tried this code but it always gives error “null is not an object”

const polygon = [
{ lat: 3.1336599385978805, lng: 101.31866455078125 },
{ lat: 3.3091633559540123, lng: 101.66198730468757 },
{ lat: 3.091150714460597, lng: 101.92977905273438 },
{ lat: 3.1336599385978805, lng: 101.31866455078125 }

let point = {
lat: 3.3091633559540123,
lng: 101.66198730468757

containsLocation(point, polygon)
.then(response => {
// if the promise was success return TRUE
console.log(‘Im inside of the polygon?’, response)
.catch(error => {
//only return FALSE if the point is not inside of the polygon
console.log(‘I am outside of the polygon?’, error)
I want to show error message if selected location is outside the city.

I’m facing the same problem. @ross.gile any luck on your side?

I would suggest searching for things like “javascript polygon contains point” or “javascript check if point is within a polygon” etc. and looking for pure JavaScript libraries that do what you want.

When I did that I came across this stack overflow question:

And from there I found turf and its booleanPointInPolygon function.

So I gave it a try and it seems to work:

expo install @turf/turf
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import * as turf from "@turf/turf";

export default function App() {
  const polygon = {
    type: "Feature",
    geometry: {
      type: "Polygon",
      coordinates: [
          [101.31866455078125, 3.1336599385978805],
          [101.66198730468757, 3.3091633559540123],
          [101.92977905273438, 3.091150714460597],
          [101.31866455078125, 3.1336599385978805]
    properties: {}
  const point = turf.point([101.66198730468757, 3.3091633559540123]);
  const pointInPoly = turf.booleanPointInPolygon(point, polygon);

  return (
    <View style={styles.container}>
      <StatusBar style="auto" />

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"

Note: I got an error which I do not understand when I used the turf.polygon() function with the above polygon, but as far as I know turf.polygon() is just a convenience function for generating GeoJSON, so including the GeoJSON directly works around the problem.

I have found ‘geolib’ library and it is working fine for me.

1 Like