Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML5 geolocation geofence location detection (without geofence API)
window.onload = function() {
var startPos;
var startPosLat;
var startPosLong;
var distance;
if (navigator.geolocation) {
startPosLat = 44.95716993150707;
startPosLong = -93.28439280496818;
$("#startLat").text(startPosLat);
$("#startLon").text(startPosLong);
navigator.geolocation.watchPosition(function(position) {
$("#currentLat").text(position.coords.latitude);
$("#currentLon").text(position.coords.longitude);
distance = calculateDistance(startPosLat, startPosLong,position.coords.latitude, position.coords.longitude)
$("#distance").text(distance);
if(distance < .05){
$("#message").text("Yes, were inside .05 KM!!! :) A+")
}else if(distance > .05){
$("#message").text("No, not inside .05 KM :(")
}
});
}
};
// 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;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="tripmeter">
<p>
Starting Location (lat, lon):<br/>
<span id="startLat">???</span>&deg;, <span id="startLon">???</span>&deg;
</p>
<p>
Current Location (lat, lon):<br/>
<span id="currentLat">locating...</span>&deg;, <span id="currentLon">locating...</span>&deg;
</p>
<p>
Distance from starting location:<br/>
<span id="distance">0</span> km
</p>
<p>
Are we here?<br/>
<span id="message">detecting....</span>
</p>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="fence.js"></script>
</body>
</html>
#tripmeter {
padding: 10px;
margin: 10px 0;
}
p {
color: #222;
font: 24px Arial;
}
span {
color: #00C;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.