Nie*_*els 16
public static List<Location> sortLocations(List<Location> locations, final double myLatitude,final double myLongitude) {
Comparator comp = new Comparator<Location>() {
@Override
public int compare(Location o, Location o2) {
float[] result1 = new float[3];
android.location.Location.distanceBetween(myLatitude, myLongitude, o.Lat, o.Long, result1);
Float distance1 = result1[0];
float[] result2 = new float[3];
android.location.Location.distanceBetween(myLatitude, myLongitude, o2.Lat, o2.Long, result2);
Float distance2 = result2[0];
return distance1.compareTo(distance2);
}
};
Collections.sort(locations, comp);
return locations;
}
Run Code Online (Sandbox Code Playgroud)
其中List of Locations是包含您自己的Location类的列表,而不是android.location.Location.
您可以使用大圆距离来计算您知道纬度 - 经度坐标的两个点之间的距离.该公式是相当容易的代码:
static double distance(double fromLat, double fromLon, double toLat, double toLon) {
double radius = 6378137; // approximate Earth radius, *in meters*
double deltaLat = toLat - fromLat;
double deltaLon = toLon - fromLon;
double angle = 2 * Math.asin( Math.sqrt(
Math.pow(Math.sin(deltaLat/2), 2) +
Math.cos(fromLat) * Math.cos(toLat) *
Math.pow(Math.sin(deltaLon/2), 2) ) );
return radius * angle;
}
Run Code Online (Sandbox Code Playgroud)
您想要定义自己的Comparator,一般来说,看起来像这样:
LonLat myHouse = /* whatever */ ;
Comparable comp = new Comparable () {
LonLat a;
int compareTo (Object b) {
int aDist = calcDistance(a, myHouse) ;
int bDist = calcDistance(b, myHouse) ;
return aDist - bDist;
}
};
myLonLatList.sort(lonLatList, comp);
Run Code Online (Sandbox Code Playgroud)
其中calcDistance()简单地计算两点之间的距离。如果您使用的是 Android,我认为 Google 地图在其 API 中的某处有一个函数可以为您执行此操作。
编辑:你会希望你的calcDistance()函数看起来像 ChrisJ 的distance函数。
-tjw
| 归档时间: |
|
| 查看次数: |
15073 次 |
| 最近记录: |