如何从位置列表中获取最近的区域? [英] How to get the nearest area from a list of locations?

查看:108
本文介绍了如何从位置列表中获取最近的区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,它返回一个城市内不同地区的清单,并显示该地区的天气情况。我想根据当前位置获得最近的区域。



API返回


  • 区域

  • 纬度

  • 经度

  • 天气

>

如何根据这些数据找到最近的面积? 您会必须为所有区域创建CLLocation对象,另外为用户的当前位置创建一个。然后使用类似于下面的循环来获取最近的位置:

  NSArray * allLocations; //这个数组包含所有你使用的API的位置的CLLocation对象

CLLocation * currentUserLocation;

CLLocation * closestLocation;
CLLocationDistance closestLocationDistance = -1;

for(CLLocation * location in allLocations){

if(!closestLocation){
closestLocation = location;
closestLocationDistance = [currentUserLocation distanceFromLocation:location];
继续;
}

CLLocationDistance currentDistance = [currentUserLocation distanceFromLocation:location];

if(currentDistance< closestLocationDistance){
closestLocation = location;
closestLocationDistance = currentDistance;


$ / code>

需要注意的一点是,这种计算方法距离使用A点和B点之间的直线。不考虑道路或其他地理对象。


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?

解决方案

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.

这篇关于如何从位置列表中获取最近的区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆