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

时间:2012-12-12 13:07:05

标签: javascript geolocation gps distance latitude-longitude

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

1 个答案:

答案 0 :(得分:38)

如果您的代码在浏览器中运行,则可以使用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米(这是硬编码的第二个位置)。

有关详细信息,请参阅以下链接: