简体   繁体   中英

Find closest longitude and latitude in array from user location - Android Studio

The following piece of code was instrumental to an iOS app I finished recently:

var closestLocation: CLLocation?
var smallestDistance: CLLocationDistance?

for location in locations {
  let distance = currentLocation.distanceFromLocation(location)
  if smallestDistance == nil || distance < smallestDistance {
    closestLocation = location
    smallestDistance = distance
  }
}

My question is pretty simple: how would this piece of code look in Java for Android Studio?

This is my first run at Java and Android Studio, so any help would be greatly appreciated.

Location closestLocation = null;
float smallestDistance = -1;

for(Location location:mLocationsList){
float distance  = currentLocation.distanceTo(location);
 if(smallestDistance == -1 || distance < smallestDistance) {
    closestLocation = location
    smallestDistance = distance
  }
}

With mLocationsList being an iterable collection of Location-objects and currentLocation being already set

You should consider using the Location class. It is used to store locations in Latitude and Longitude. It also has predefined function for calculating distance between points - distanceBetween() .

Location closestLocation;
int smallestDistance = -1;

Assuming locations is an 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;
    }
}

It would look something like this (locations need to be iterable and userLocation must be set):

    Location closest;
    float smallestDistance = Float.MAX_VALUE;
    for (Location l : locations) {
        float dist = l.distanceTo(userLocation);
        if (dist < smallestDistance) {
            closest = l;
            smallestDistance = dist;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM