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

如何在JavaScript中查找到已知位置的距离,javascript,geolocation,gps,distance,latitude-longitude,Javascript,Geolocation,Gps,Distance,Latitude Longitude,在浏览器中使用JavaScript,如何确定从我的当前位置到另一个我有纬度和经度的位置的距离?如果您的代码在浏览器中运行,您可以使用HTML5地理位置API: window.navigator.geolocation.getCurrentPosition(function(pos) { console.log(pos); var lat = pos.coords.latitude; var lon = pos.coords.longitude; }) 一旦您知道当前位置和“目标

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

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

window.navigator.geolocation.getCurrentPosition(function(pos) { 
  console.log(pos); 
  var lat = pos.coords.latitude;
  var lon = pos.coords.longitude;
})
一旦您知道当前位置和“目标”的位置,您就可以按照此问题中记录的方式计算它们之间的距离:

因此,完整的脚本变成:

功能距离(lon1、lat1、lon2、lat2){
var R=6371;//地球半径,单位为km
var dLat=(lat2-lat1).toRad();//以弧度表示的Javascript函数
var dLon=(lon2-lon1.toRad();
变量a=Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.cos(lat1.toRad())*Math.cos(lat2.toRad())*
数学单(dLon/2)*数学单(dLon/2);
var c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
var d=R*c;//以公里为单位的距离
返回d;
}
/**将数字度转换为弧度*/
if(typeof(Number.prototype.toRad)=“未定义”){
Number.prototype.toRad=函数(){
返回这个*Math.PI/180;
}
}
window.navigator.geolocation.getCurrentPosition(函数(pos)){
控制台日志(pos);
console.log(
距离(位置坐标经度,位置坐标纬度,42.37,71.03)
); 
});
显然,我现在距离马萨诸塞州波士顿市中心6643米(这是硬编码的第二个位置)

有关更多信息,请参见以下链接:


非常感谢。我还有一个问题。你能帮我找到一个地方的经纬度吗?我在试着找到从我现在的位置到一个特定地址的距离。反正我找到了。谢谢你的回复。嗨@Frank,非常感谢你的脚本——这个脚本测试得好吗?@Frankvanpoffelen当经度或纬度的值为负时,结果似乎不准确。