如何在 JavaScript 中找到我到已知位置的距离

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13840516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:54:19  来源:igfitidea点击:

How to find my distance to a known location in JavaScript

javascriptgeolocationgpsdistancelatitude-longitude

提问by Dalee

Using JavaScript in the browser, how can I determine the distance from my current location to another location for which I have the latitude and longitude?

在浏览器中使用 JavaScript,如何确定从我的当前位置到我有纬度和经度的另一个位置的距离?

回答by Frank van Puffelen

If your code runs in a browser, you can use the HTML5 geolocation API:

如果您的代码在浏览器中运行,您可以使用 HTML5 地理定位 API:

window.navigator.geolocation.getCurrentPosition(function(pos) { 
  console.log(pos); 
  var lat = pos.coords.latitude;
  var lon = pos.coords.longitude;
})

Once you know the current position and the position of your "target", you can calculate the distance between them in the way documented in this question: Calculate distance between two latitude-longitude points? (Haversine formula).

一旦您知道当前位置和“目标”的位置,您就可以按照这个问题中记录的方式计算它们之间的距离:计算两个经纬度点之间的距离?(Haversine 公式)

So the complete script becomes:

所以完整的脚本变成了:

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)
  ); 
});

Apparently I am 6643 meters from the center of Boston, MA right now (that's the hard-coded second location).

显然,我现在距离马萨诸塞州波士顿市中心 6643 米(这是硬编码的第二个位置)。

See these links for more information:

有关更多信息,请参阅这些链接: