我想知道如何从给定的浮点值中获取最近的位置。
我有一个具有纬度/经度的城市ArrayList。我想做的是从给定坐标找到最近的城市。
public class City {
private float lat;
private float lng;
//getters & setters
}
List < City > cities; // at this point "cities" contains several "city"
City city;
city = findNearest(lat, lng);
private City findNearest(float lat, float lng) {
for (City c: cities) {}
}
答案 0 :(得分:4)
尝试计算简单偏差:
private City findNearest(float lat, float lng) {
float minDist = Float.MAX_VALUE;
City resCity = null;
for (City c: cities) {
float dist = Math.pow(c.getLat() - lat, 2) + Math.pow(c.getLng() - lng, 2);
if (dist < minDist){
minDist = dist;
resCity = c;
}
}
return resCity;
}
你可以从dist获取Math.sqrt,但实际上没有任何意义。