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

笑着哭i 提交于 2019-11-30 10:39:34

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.

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