Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

geofencing javascript example

//You can watch using geoposition. navigator.geolocation.watchPosition

//here example with SquareGeofenceRegion & CircularGeofenceRegion

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);
Comment

PREVIOUS NEXT
Code Example
Javascript :: jquery alert design 
Javascript :: how to show bootstrap 5 modal using jquery 
Javascript :: js canvas rectangel 
Javascript :: get random element from array js 
Javascript :: convert map to object/JSON javascript 
Javascript :: ajax get form data 
Javascript :: javascript seconds to date 
Javascript :: find in array react 
Javascript :: duplicate an array in javascript n times 
Javascript :: curl post json file 
Javascript :: flattenDeep in es 6 without lodash 
Javascript :: express get client ip 
Javascript :: javascript check if date object 
Javascript :: javascript get hour from date 
Javascript :: string.find javascript 
Javascript :: lottie react 
Javascript :: sum numbers recursively js 
Javascript :: map to array javascript 
Javascript :: jquery get URL slug 
Javascript :: search no of item in array 
Javascript :: react native new line character 
Javascript :: Finding HTML Element by Id 
Javascript :: nuxt lang 
Javascript :: javascript colorized console.log 
Javascript :: javascript newline in alert box 
Javascript :: node.js for windows 7 
Javascript :: Get the Status Code of a Fetch HTTP Response 
Javascript :: js filter array of objects by value 
Javascript :: jquery set html of element 
Javascript :: mongoose limit 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =