Skip to content

Instantly share code, notes, and snippets.

@MondeLionel
Forked from bmoren/fence.js
Last active October 3, 2020 11:27
Show Gist options
  • Save MondeLionel/da3ed6cc97f9ef6618bd49d1be963ce7 to your computer and use it in GitHub Desktop.
Save MondeLionel/da3ed6cc97f9ef6618bd49d1be963ce7 to your computer and use it in GitHub Desktop.
HTML5 geolocation geofence location detection (without geofence API)
/* PLEASE NOTE
THE JS HAS BEEN ALTERED FOR RELEVANCE - simply copy and paste into your own JS and watch the console.
THE HTML AND CSS ARE WHOLLY UNUSED FOR THIS PARTICULAR CASE
please refer to the original gist here: https://gist.github.com/bmoren/22470de1cd47410e0902 for relevant jquery selectors and stuff.
*/
window.onload = function() {
var startPos;
var startPosLat;
var startPosLong;
var distance;
// Check if browser has geolocation capability
if (navigator.geolocation) {
startPosLat = 44.95716993150707; //target latitude of Type:Number
startPosLong = -93.28439280496818; // target longitude of Type:Number
// We dont need to watch position. just get the position on page load, ONCE!
/*
navigator.geolocation.getCurrentPosition(success, error, options);
*/
let success = function(position) {
// get the current position of the device
console.log(position.coords.latitude + " is my current latitude");
console.log(position.coords.longitude+ " is my current longitude");
// Calculate distance function to compare difference between your start position and where you are.
distance = calculateDistance(startPosLat, startPosLong,position.coords.latitude, position.coords.longitude)
console.log(distance);
// SUBSIDE, BRUHERIA!
// Do what you want, play around
if(distance < .05){
console.log("Yes, were inside .05 KM!!! :) A+")
}
if(distance > .05){
console.log("No, not inside .05 KM :(")
}
}
// Create an optional error handler
let error = function(err){
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error);
}
};
// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
// http://www.movable-type.co.uk/scripts/latlong.html
// Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment