I have got a location of a venue with these long/lat parameters: 51.4625733,-0.1868911
I am trying to find a jquery solution when user is close to this venue - let's say 100 meter then a message/alert should be displayed.
I am using this example to get a distance but it doesn't seem working correctly.
function distance(lon1, lat1, lon2, lat2) {
var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1).toRad(); // Javascript functions in radians
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; // Distance in km
return d;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
console.log(
distance(pos.coords.longitude, pos.coords.latitude, 51.4625733, -0.1868911)
);
});
Your help is really appreciated.
I found a solution for this task so put it down for anyone who can find it useful.
// convert numeric degress to radians
toRad = function (value) {
return value * Math.PI / 180;
};
Equirectangular = function (point1, point2) {
var R = 6371; // earth radius in km
var x = (toRad(point2.lon) - toRad(point1.lon)) * Math.cos((toRad(point1.lat) + toRad(point2.lat)) / 2);
var y = (toRad(point2.lat) - toRad(point1.lat));
return Math.sqrt(x * x + y * y) * R;
};
// START HERE
window.navigator.geolocation.getCurrentPosition(function (pos) {
pointOne = {
lat: pos.coords.latitude,
lon: pos.coords.longitude
};
pointTwo = {
lat: 51.4625733,
lon: -0.1868911
};
x = Equirectangular(pointOne, pointTwo);
d = 10; // in kilometers
if (d == x || d > x) {
$('body').append('<p><b>you are very close</b><br>' + x);
} else {
$('body').append('<br>' + x);
}
});