我有一个具有这些长/纬度参数的场地位置:51.4625733,-0.1868911
当用户离这个场地很近时,我试图找到一个jquery解决方案 - 让我们说100米然后应该显示一条消息/警报。
我正在使用此示例来获得距离,但它似乎无法正常工作。
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)
);
});
非常感谢您的帮助。
答案 0 :(得分:0)
我为这项任务找到了一个解决方案,所以对于那些能发现它有用的人来说。
// 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);
}
});