3

I'm working on a project using HTML5 Geolocation API and currently using socket.io to allow user locate others in a remote location. Now for my next target is I want my application to create some sort of a geofencing that sends notification if users are outside of the boundary.

Now my Question is:

  • Can I do it without using any database?
  • Is it possible to use only Javascript?

I'm using Google maps if anyone is asking

3

1 Answer 1

10

There is a way for you to watch for changes in geoposition. navigator.geolocation.watchPosition

But there is no geofencing api available, so you have to create that yourself:

I made two classes: SquareGeofenceRegion & CircularGeofenceRegion that have the same api's but is calculated differently.

class CircularGeofenceRegion {
  constructor(opts) {
    Object.assign(this, opts)
  }

  inside(lat2, lon2) {
    const lat1 = this.latitude
    const lon1 = this.longitude
        const R = 63710; // Earth's radius in m

    return Math.acos(Math.sin(lat1)*Math.sin(lat2) + 
                     Math.cos(lat1)*Math.cos(lat2) *
                     Math.cos(lon2-lon1)) * R < this.radius;
  }
}

class SquareGeofenceRegion {
  constructor(opts) {
    Object.assign(this, opts)
  }

  inside(lat, lon) {
    const x = this.latitude
    const y = this.longitude
    const { axis } = this

    return lat > (x - axis) && 
           lat < (x + axis) &&
           lon > (y - axis) &&
           lon < (y + axis)
  }
}

const fenceA = new CircularGeofenceRegion({
  name: 'myfence',
  latitude: 59.345635,
  longitude: 18.059707,
  radius: 1000 // meters
});

const fenceB = new SquareGeofenceRegion({
  name: 'myfence',
  latitude: 59.345635,
  longitude: 18.059707,
  axis: 1000 // meters in all 4 directions
})

const fences = [fenceA, fenceB]
const options = {}

navigator.geolocation.watchPosition(({coords}) => {
  for (const fence of fences) {
    const lat = coords.latitude
    const lon = coords.longitude

    if (fence.inside(lat, lon)) {
      // do some logic
    }
  }
}, console.error, options);

I just want to warn you that the watchPosition may not always be trigger while it's in the background: It is possible to watch the location in the background on Mobile (iOS / Android)?

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.