如何在JavaScript中找到我与已知位置的距离 [英] How to find my distance to a known location in JavaScript
问题描述
在浏览器中使用JavaScript,如何确定从当前位置到另一个具有经度和纬度的位置的距离? 解决方案
如果您的代码在浏览器中运行,您可以使用HTML5地理定位API:
window.navigator。 geolocation.getCurrentPosition(function(pos){
console.log(pos);
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
})
一旦您知道了目标的当前位置和位置,就可以计算他们之间的距离按照这个问题中记录的方式:计算两个纬度经度点之间的距离? (Haversine公式)。
因此,完整的脚本变成:
函数距离(lon1,lat1,lon2,lat2){
var R = 6371; //以公里为单位的地球半径
var dLat =(lat2-lat1).toRad(); //以弧度表示的Javascript函数
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; //以公里为单位的距离
返回d;
$ **
$ b / **将数值度数转换为弧度* /
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
距离(pos.coords.longitude,pos.coords.latitude,42.37,71.03)
);
});
显然,我现在距马萨诸塞州波士顿市中心6643米(这是硬编码的第二
请参阅以下链接以获取更多信息:
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?
If your code runs in a browser, you can use the HTML5 geolocation 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).
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).
See these links for more information:
- http://html5demos.com/geo
- http://diveintohtml5.info/geolocation.html
- Calculate distance between two latitude-longitude points? (Haversine formula)
- toRad() Javascript function throwing error
这篇关于如何在JavaScript中找到我与已知位置的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!