How to get the nearest area from a list of locations?

爷,独闯天下 提交于 2019-11-29 15:52:43

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!