【问题标题】:How to find my distance to a known location in JavaScript如何在 JavaScript 中找到我到已知位置的距离
【发布时间】:2012-11-30 04:50:39
【问题描述】:

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

【问题讨论】:

    标签: javascript geolocation gps distance latitude-longitude


    【解决方案1】:

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

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

    一旦您知道“目标”的当前位置和位置,您就可以按照此问题中记录的方式计算它们之间的距离:Calculate distance between two latitude-longitude points? (Haversine formula)

    所以完整的脚本变成了:

    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 米(这是硬编码的第二个位置)。

    查看这些链接了解更多信息:

    【讨论】:

    • 非常感谢。我还有一个疑问。你能帮我找到给定地点的纬度和经度吗?
    • 我试图找出从我当前位置到特定地址的距离。反正我发现了。感谢您的回复。
    • 嗨@Frank,非常感谢这个脚本——这个脚本测试好了吗?
    • @FrankvanPuffelen 当经度或纬度的值为负时,结果似乎不准确。
    • 我建议您更改参数的顺序,使纬度在经度之前,因为通常地理点以格式(纬度,经度)显示。
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    相关资源
    最近更新 更多