如何从位置列表中获取最近的区域



我有一个API,它返回城市内不同区域的列表以及该地区的天气。我想根据我当前的位置获取最近的区域。

接口返回

  • 面积
  • 纬度
  • 经度
  • 天气

如何根据这些数据找到最近的区域?

您必须为所有区域创建一个 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 点之间使用直线。

最新更新