计算两个纬度 - 经度点之间的距离? - 钛

时间:2016-09-23 06:41:07

标签: titanium hybrid-mobile-app

我尝试使用此代码。

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

Titanium.Geolocation.getCurrentPosition(function(e) { 
  Ti.API.info(distance(e.coords.longitude, e.coords.latitude, 10.0009768, 76.2369564)); 
});

但是,它没有显示实际距离。有人请帮助我找到解决方案。

2 个答案:

答案 0 :(得分:0)

这对我有用。

function getDistance(lat1, lon1, lat2, lon2) { 

    Ti.API.info('***Distance ='+lat1, lon1, lat2, lon2);
    var radlat1 = Math.PI * lat1 / 180;
    var radlat2 = Math.PI * lat2 / 180;
    var theta = lon1 - lon2;
    var radtheta = Math.PI * theta / 180;
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist);
    dist = dist * 180 / Math.PI;
    dist = dist * 60 * 1.1515;
    dist = dist.toFixed(0);
    Ti.API.info('dist ='+dist);
    return dist;
}

谢谢。

答案 1 :(得分:0)

你的第一个代码中的

使用了这个:

var c = 2 * Math.asin(Math.sqrt(a))

http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe