2015-05-29 116 views
0

如何根據給定距離(以公里爲單位)從經度和緯度的另一個城市過濾給定的經度和緯度城市列表。過濾城市的經緯度與其他城市的距離(經緯度)?

我想使用Google Maps API(javascript)或其他適合的解決方案。

cities = { 
      ['zürich','47.368650', '8.539183'], 
      ['City2','21.568650', '2.439183'], 
      ['City3','41.568650', '4.439183'] 
} 


distance = 2; //2 km 
targetCity = ['zürich','47.368650', '8.539183']; 

需要:getNearCities(targetCity,distance,cities);

謝謝

+0

你可以看到這個頁面http://www.movable-type.co.uk/scripts/latlong上haversine公式。 html –

+0

查看google距離矩陣api https://developers.google.com/maps/documentation/distancematrix/ – Ronin

回答

0

時退房google.maps.geometry.spherical namespace創建LatLng對象。用它你可以得到兩點之間的距離。

var origin = new google.maps.LatLng(###,###); 
var destination = new google.maps.LatLng(###,###); 
var maxDistance = 2; //in km 

var withinRange = (google.maps.geometry.spherical.computeDistanceBetween(origin, destination) <= maxDistance); 
0

幸得http://www.geodatasource.com/developers/javascript

var cities = [ 
    ['zürich', 47.368650, 8.539183], 
    ['City2', 21.568650, 2.439183], 
    ['City3', 41.568650, 4.439183] 
]; 

var dist = calculateDistance(cities[0][2], cities[0][3], cities[1][4], cities[1][5], 'K'); 
alert(dist); 

function calculateDistance(lat1, lon1, lat2, lon2, unit) { 
    var radlat1 = Math.PI * lat1/180 
    var radlat2 = Math.PI * lat2/180 
    var radlon1 = Math.PI * lon1/180 
    var radlon2 = Math.PI * lon2/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 
    if (unit == "K") { 
     dist = dist * 1.609344 
    } 
    if (unit == "N") { 
     dist = dist * 0.8684 
    } 
    return dist + unit 
} 

JsFiddle