Ios 从用户位置查找阵列中最近的经度和纬度
我有一个充满经度和纬度的阵列。我的用户位置有两个双变量。我想根据我的阵列测试用户位置之间的距离,看看哪个位置最近。我该怎么做 这将得到2个位置之间的距离,但要理解会有困难 我如何根据一系列位置测试它Ios 从用户位置查找阵列中最近的经度和纬度,ios,objective-c,mkmapview,cllocationmanager,cllocationdistance,Ios,Objective C,Mkmapview,Cllocationmanager,Cllocationdistance,我有一个充满经度和纬度的阵列。我的用户位置有两个双变量。我想根据我的阵列测试用户位置之间的距离,看看哪个位置最近。我该怎么做 这将得到2个位置之间的距离,但要理解会有困难 我如何根据一系列位置测试它 CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:userlatitude longitude:userlongitude]; CLLocation *endLocation = [[CLLocation alloc]
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];
您只需要遍历数组,检查距离
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;
}
}
NSArray*locations=//您的CLLocation对象数组
CLLocation*currentLocation=//当前设备位置
CLLocation*闭合位置;
CLLocationDistance smallestDistance=双最大值;
用于(CLLocation*位置中的位置){
CLLocationDistance=[currentLocation distanceFromLocation:location];
if(距离<最小距离){
最小距离=距离;
闭合位置=位置;
}
}
在循环结束时,您将拥有最小的距离和最近的位置。@Fogmeister
我认为这是一个关于DBL_MAX和赋值的错误,必须纠正
首先:使用DBL\u MAX而不是DOUBLE\u MAX
DBL_MAX是math.h中的一个定义变量。它是最大可表示的有限浮点数(双精度)的值 第二:在您的情况下,您的作业是错误的:
if (distance < smallestDistance) {
distance = smallestDistance;
closestLocation = location;
}
if(距离
你必须做到:
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
if(距离
不同之处在于将距离值指定为smallestDistance,而不是相反
最终结果:
NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location
CLLocation *closestLocation;
CLLocationDistance smallestDistance = DBL_MAX; // set the max value
for (CLLocation *location in locations) {
CLLocationDistance distance = [currentLocation distanceFromLocation:location];
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
}
NSLog(@"smallestDistance = %f", smallestDistance);
NSArray*locations=//您的CLLocation对象数组
CLLocation*currentLocation=//当前设备位置
CLLocation*闭合位置;
CLLocationDistance smallestDistance=DBL_MAX;//设置最大值
用于(CLLocation*位置中的位置){
CLLocationDistance=[currentLocation distanceFromLocation:location];
if(距离<最小距离){
最小距离=距离;
闭合位置=位置;
}
}
NSLog(@“smallestDistance=%f”,smallestDistance);
你能确认这是正确的吗 DOUBLE_MAX变量用于什么?DOUBLE_MAX将
smallestDistance
变量设置为可能的最大值。您可以将其设置为任何值,但如果最初将其设置为100
,那么如果与阵列的最小距离实际上是150
@Fogmeister,您是否应该更新“smallestDistance”而不是“distance”?