DEV Community

Cover image for create geofencing in react | computeDistanceBetween & containsLocation
HasOne
HasOne

Posted on

create geofencing in react | computeDistanceBetween & containsLocation

You may find a situation where you need to create a google map and google place autocomplete and limit your service to 5KM radius from a specific address like 5KM around Miami we offer our service, let's learn how we can achieve this

Radius

Screenshot 2021-09-04 at 00.54.45

We'll be using react-google-autocomplete to show autosuggest address while you type, but we need google-place api to get it to work. now create a radius and check if the address contain inside that radius or not.

import Autocomplete from "react-google-autocomplete";


const onPlaceSelectedHandler = (place) => {
    const newAddress = {
      lat: place.geometry.location.lat(),
      lng: place.geometry.location.lng(),
    };

    // create center point; Miami
    const center = new window.google.maps.LatLng(25.4844904, -80.4616389);

    // user selected address
    const to = new window.google.maps.LatLng(
      place.geometry.location.lat(),
      place.geometry.location.lng()
    );

    // now check the distance between two address, is it inside 50Miles 
    const contains =
      window.google.maps.geometry.spherical.computeDistanceBetween(
        center,
        to
      ) <= 8046.72; // meters it's 5Miles

   if (contains) { console.log('go ahead how can we help you') }
   else { console.log('Sorry we do not offer our service yet') }

  }


return (
 <Autocomplete
      apiKey={process.env.REACT_APP_MAP_API}
      className={classes.autocomplete}
      onPlaceSelected={onPlaceSelected}
      componentRestrictions={{ country: "us" }}
      options={{
        types: ["geocode", "establishment"],
      }}
    />
)

Enter fullscreen mode Exit fullscreen mode

computeDistanceBetween(from, to) each argument need latitude and longitude, provide the lat and lng of center and the selected address lat and lng it will return the distance between two point in meters now you make a condition if the retuned meter is less than your 8046.72 (5KM). that's it

Polygon

Screenshot 2021-09-04 at 02.10.09

this is how you can create polygon, you need to collect the lat and lng from all the points and then check it the user selected address contains inside that polygon.

const onPlaceSelectedHandler = (place) => {
        const newAddress = {
            lat: place.geometry.location.lat(),
            lng: place.geometry.location.lng(),
        };

        var polygonCoords = [
            { lat: -33.83585327701507, lng: 151.2809005901216 },
            { lat: -33.73335715102409, lng: 150.8744770943904 },
            { lat: -33.82163832733159, lng: 150.8404448193081 },
            { lat: -33.9974469167501, lng: 151.247420749521 },
            { lat: -33.83585327701507, lng: 151.2809005901216 },
        ];

        var polygon = new window.google.maps.Polygon({
            paths: polygonCoords,
        });

        const contains = window.google.maps.geometry.poly.containsLocation(
            new window.google.maps.LatLng(newAddress.lat, newAddress.lng),
            polygon
        );

       if (contains) { console.log('go ahead how can we help you') }
       else { console.log('Sorry we do not offer our service yet') }
    }

return (
 <Autocomplete
      apiKey={process.env.REACT_APP_MAP_API}
      className={classes.autocomplete}
      onPlaceSelected={onPlaceSelected}
      componentRestrictions={{ country: "us" }}
      options={{
        types: ["geocode", "establishment"],
      }}
    />
)
Enter fullscreen mode Exit fullscreen mode

Thank you for making it to here.

I hope it helped, helpful links:
1) http://jsfiddle.net/5wrejxnm/
2) http://jsfiddle.net/qy7yr/
3) https://developers.google.com/maps/documentation/javascript/reference/geometry#spherical.computeDistanceBetween
4) https://stackoverflow.com/questions/46762911/how-to-use-computedistancebetween
5) https://stackoverflow.com/questions/36640449/google-maps-api-a-lat-is-not-a-function-error

Polygon
6) http://jsfiddle.net/mrummler/x942cyg6/
7) https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
8) https://jsfiddle.net/geocodezip/yqLvjf8z/2/
9) https://jsfiddle.net/iselwin/pcduogka/
10) https://stackblitz.com/edit/react-gvavr9?file=Map.js

Top comments (0)