如何按距离ASC排序我的阵列结果?
我需要根据我的地理坐标(纬度/经度)对循环进行排序
请参阅我的代码:
function calculateDistance(lat1, lon1, lat2, lon2)
{
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
dist = dist * 1.609344 * 1000
return Math.round(dist)
}
function places()
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM places', [], function (tx, results) {
for (i = 0; i < results.rows.length; i++)
{
var distance = calculateDistance(mylat, mylng, results.rows.item(i).lat, results.rows.item(i).lng);
}
}, null);
});
}
答案 0 :(得分:1)
您可以计算结果在循环内的距离,然后排序:
for (i = 0; i < results.rows.length; i++) {
results.rows[i].distance = calculateDistance(mylat, mylng, results.rows.item(i).lat, results.rows.item(i).lng);
}
results.rows.sort(function(a, b) {
return a.distance - b.distance;
})