地点
Sorting of locations ref. nearest location.
按距离排序地点
它是如何工作的?
- 获取用户当前位置
- 与其他目的地进行比较
- 按最近的排序
有两种比较距离的方法
我个人喜欢并一直在使用 Haversine 公式。
算法 1
使用 Haversine 公式。
Haversine 公式
double getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
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;
}
double deg2rad(deg) {
return deg * (Math.pi/180);
}
算法 2
使用 Geolocater 提供的内置距离比较函数。
Geolocator.distanceBetween(source.latitude,source.longitude, destination.latitude,destination.longitude);
假设
- 你在 Google Plex (37.422,-122.084)
目的地
- 目的地(37.4274684,-122.1698161, "斯坦福大学"),
- 目的地(37.4083327,-122.0776016, "Taco Bell"),
- 目的地(37.4259071,-122.1095606, "拉莫斯公园"),
- 目的地(37.8711583,-122.336457, "伯克利"),
- 目的地(37.7586968,-122.3053474, "奥克兰"),
- 目的地(37.4420794,-122.1432758, "Palo Alto"),
- 目的地(37.5206515,-122.064364, "Newark")
输出
| Haversine 算法 | Geolocator 算法 |
|---|---|
![]() |
![]() |

