我有一个API,它返回一个城市内不同区域的列表,其中包含该区域的天气。我想根据我当前的位置得到最近的区域。
API返回
如何根据这些数据找到最近的区域?
答案 0 :(得分:6)
您必须为所有区域创建CLLocation对象,并为用户的当前位置创建一个CLLocation对象。然后使用类似于下面的循环来获得最近的位置:
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;
}
}
有一点需要注意的是,这种计算距离的方法使用了A点和B点之间的直线。没有考虑道路或其他地理对象。