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

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

API返回

  • 纬度
  • 经度
  • 天气

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

你将不得不为所有区域创buildCLLocation对象,加上一个用于当前位置的用户。 然后使用类似于下面的循环来获取最近的位置:

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之间的直线。不考虑道路或其他地理对象。