从用户位置查找数组中最接近的经度和纬度 [英] Find closest longitude and latitude in array from user location
本文介绍了从用户位置查找数组中最接近的经度和纬度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个充满经度和纬度的数组.我的用户位置有两个双精度变量.我想根据数组测试用户位置之间的距离,以查看哪个位置最近.我该怎么做?
I have an array full of longitudes and latitudes. I have two double variables with my users location. I'd like to test the distance between my user's locations against my array to see which location is the closest. How do I do this?
这将获得2个位置之间的距离,但努力理解 我如何针对一系列位置进行测试.
This will get the distance between 2 location but stuggeling to understand how I'd test it against an array of locations.
CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:userlatitude longitude:userlongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation];
推荐答案
您只需要遍历数组以检查距离即可.
You just need to iterate through the array checking the distances.
NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location
CLLocation *closestLocation;
CLLocationDistance smallestDistance = DOUBLE_MAX;
for (CLLocation *location in locations) {
CLLocationDistance distance = [currentLocation distanceFromLocation:location];
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
}
在循环结束时,您将拥有最小的距离和最近的位置.
At the end of the loop you will have the smallest distance and the closest location.
这篇关于从用户位置查找数组中最接近的经度和纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文