Jack Clarkson
Jack Clarkson

Reputation: 105

html5 Geolocation API with Geofencing

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:

I'm using Google maps if anyone is asking

Upvotes: 3

Views: 6572

Answers (1)

Endless
Endless

Reputation: 37855

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)?

Upvotes: 11

Related Questions