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
- Area
- Latitude
- Longitude
- Weather
How to find the nearest area based on this data?
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.
来源:https://stackoverflow.com/questions/12027558/how-to-get-the-nearest-area-from-a-list-of-locations