以下代码对我最近完成的iOS应用程序起了作用:
var closestLocation: CLLocation?
var smallestDistance: CLLocationDistance?
for location in locations {
let distance = currentLocation.distanceFromLocation(location)
if smallestDistance == nil || distance < smallestDistance {
closestLocation = location
smallestDistance = distance
}
}
我的问题非常简单:这段代码如何在Java for Android Studio中显示?
这是我第一次在Java和Android Studio上运行,因此非常感谢任何帮助。
答案 0 :(得分:2)
Location closestLocation = null;
float smallestDistance = -1;
for(Location location:mLocationsList){
float distance = currentLocation.distanceTo(location);
if(smallestDistance == -1 || distance < smallestDistance) {
closestLocation = location
smallestDistance = distance
}
}
mLocationsList
是位置对象的可迭代集合,currentLocation
已设置
答案 1 :(得分:2)
您应该考虑使用Location类。它用于存储纬度和经度的位置。它还具有用于计算点之间距离的预定义函数 - distanceBetween()
。
Location closestLocation;
int smallestDistance = -1;
假设地点是ArrayList<Location>()
for(Location location : locations){
int distance = Location.distanceBetween(closestLocation.getLatitude(),
closestLocation.getLongitude(),
location.getLatitude(),
location.getLongitude());
if(smallestDistance == -1 || distance < smallestDistance){
closestLocation = location;
smallestDistance = distance;
}
}
答案 2 :(得分:1)
看起来像这样(位置需要迭代,必须设置userLocation):
Location closest;
float smallestDistance = Float.MAX_VALUE;
for (Location l : locations) {
float dist = l.distanceTo(userLocation);
if (dist < smallestDistance) {
closest = l;
smallestDistance = dist;
}
}