在浏览器中使用 JavaScript,如何确定从我当前位置到另一个我有纬度和经度的位置的距离?
如果您的代码在浏览器中运行,您可以使用 HTML5 地理定位 API:
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
})
一旦您知道当前位置和“目标”的位置,您就可以按照本问题中记录的方式计算它们之间的距离:计算两个经纬度点之间的距离? (半正矢公式) https://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points.
所以完整的脚本变成:
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, 42.37, 71.03)
);
});
显然我现在距离马萨诸塞州波士顿市中心 6643 米(这是硬编码的第二个位置)。
请参阅这些链接以获取更多信息:
- http://html5demos.com/geo http://html5demos.com/geo
- http://diveintohtml5.info/geolocation.html http://diveintohtml5.info/geolocation.html
- 计算两个经纬度点之间的距离? (半正矢公式) https://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points
- toRad() Javascript 函数抛出错误 https://stackoverflow.com/questions/5260423/torad-javascript-function-throwing-error
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)