以下代码对我最近完成的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上运行,因此将不胜感激。

最佳答案

您应该考虑使用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;
    }
}

10-08 18:24