2013-07-11 76 views

回答

4

this site,您可以使用haversine公式:

a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2) 
c = 2.atan2(√a, √(1−a)) 
d = R.c 

這可以在Javascript實現:

var R = 6371; // km 
var dLat = (lat2-lat1).toRad(); 
var dLon = (lon2-lon1).toRad(); 
var lat1 = lat1.toRad(); 
var lat2 = lat2.toRad(); 

var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c; 

然後,只需做到這一點對所有的城市使用一個循環,並找到最小的。

+1

非常感謝!我需要添加:'Number.prototype.toRad = function(){return this * Math.PI/180; }'在這裏提到:http://stackoverflow.com/questions/6889922/how-to-deal-with-brng-torad-is-not-a-function – rttmax

相關問題