Reputation: 45
I have a API which returns a list of different areas within a city with the weather at that area. I want to get the nearest area based on my current location.
API returns
How to find the nearest area based on this data?
Upvotes: 0
Views: 3472
Reputation: 16946
You would have to create CLLocation objects for all the areas, plus one for the current location of the user. Then use a loop similar to the one below to get the closest location:
NSArray *allLocations; // this array contains all CLLocation objects for the locations from the API you use
CLLocation *currentUserLocation;
CLLocation *closestLocation;
CLLocationDistance closestLocationDistance = -1;
for (CLLocation *location in allLocations) {
if (!closestLocation) {
closestLocation = location;
closestLocationDistance = [currentUserLocation distanceFromLocation:location];
continue;
}
CLLocationDistance currentDistance = [currentUserLocation distanceFromLocation:location];
if (currentDistance < closestLocationDistance) {
closestLocation = location;
closestLocationDistance = currentDistance;
}
}
One thing to note is that this method of calculating a distance uses a direct line between point A and point B. No roads or other geographical objects are taken into account.
Upvotes: 6