我有一个由以下数组对象填充的 ListActivity:
public class VideoLocation {
public String deleted_at = null;
public int documentary_video_length = -1;
public int id = -1;
public double latitude = 0d;
public double longitude = 0d;
public int position = -1;
public String updated_at = null;
public String name = null;
public String text = null;
public String documentary_video_url = null;
public String documentary_thumbnail_url = null;
public String audio_text_url = null;
public Footage[] footages = null;
public VideoLocation(){
}
我需要根据位置和用户之间的距离对 ListActivity 进行排序。我按字母顺序对“名称”字符串进行排序没有任何问题,我使用这种方法:
public void sortAZ(){
Arrays.sort(videoLocations, new Comparator<VideoLocation>() {
@Override
public int compare(VideoLocation lhs, VideoLocation rhs) {
return lhs.name.compareTo(rhs.name);
}
});
}
但该方法不能用于“双”数据类型,我需要“纬度”和“经度”。此外,对象 VideoLocation 没有属性“距离”。
即使我可以计算位置和用户之间的距离,我如何才能解决它?
更新
这是最终解决方案!奇迹般有效
public void sortNearby(){
Arrays.sort(videoLocations, new Comparator<VideoLocation>() {
@Override
public int compare(VideoLocation lhs, VideoLocation rhs) {
double lat = location.getLatitude();
double lng = location.getLongitude();
double lat1 = lhs.latitude;
double lng1 = lhs.longitude;
double lat2 = rhs.latitude;
double lng2 = rhs.longitude;
double lhsDistance = countDistance(lat,lng,lat1,lng1);
double rhsDistance = countDistance(lat,lng,lat2,lng2);
if (lhsDistance < rhsDistance)
return -1;
else if (lhsDistance > rhsDistance)
return 1;
else return 0;
}
});
}
public double countDistance(double lat1,double lng1, double lat2, double lng2)
{
Location locationUser = new Location("point A");
Location locationPlace = new Location("point B");
locationUser.setLatitude(lat1);
locationUser.setLongitude(lng1);
locationPlace.setLatitude(lat2);
locationPlace.setLongitude(lng2);
double distance = locationUser.distanceTo(locationPlace);
return distance;
}