Reputation: 549
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.
Upvotes: 1
Views: 9550
Reputation: 1963
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
Upvotes: 2
Reputation: 11330
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;
}
}
Upvotes: 4
Reputation: 2947
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;
}
}
Upvotes: 1