gpt4 book ai didi

ios - 从用户位置 ios 查找最近的注释?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:06:01 25 4
gpt4 key购买 nike

我有一组注释。我正在计算每个注释与用户位置之间的距离。我想知道的是,我怎样才能找到距离这些距离最近的 3 个注释?

这是我计算从用户位置到注释的距离的方法。

  CLLocation *userLocation = self.mapView.userLocation.location;

for (Annotation *obj in annotations) {

CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude];
// CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance dist = [loc distanceFromLocation:userLocation];
int distance = dist;
NSLog(@"Distance from Annotations - %i", distance);


}

最佳答案

userLocation 是静态的,所以不要在循环中每次都重新创建它。您还可以通过以下方式直接获取位置:

CLLocation *userLocation = self.mapView.userLocation.location;

然后,您可以执行类似的操作,将您的距离数字和注释存储到字典中,将距离作为键,将注释作为值。构建字典后,对 allKeys 数组进行排序,然后您可以获得与前 3 个键关联的注释。


假设您在运行此命令时始终至少有一个注释:

CLLocation *userLocation = self.mapView.userLocation.location;
NSMutableDictionary *distances = [NSMutableDictionary dictionary];

for (Annotation *obj in annotations) {
CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude];
CLLocationDistance distance = [loc distanceFromLocation:userLocation];

NSLog(@"Distance from Annotations - %f", distance);

[distances setObject:obj forKey:@( distance )];
}

NSArray *sortedKeys = [[distances allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *closestKeys = [sortedKeys subarrayWithRange:NSMakeRange(0, MIN(3, sortedKeys.count))];

NSArray *closestAnnotations = [distances objectsForKeys:closestKeys notFoundMarker:[NSNull null]];

关于ios - 从用户位置 ios 查找最近的注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22452509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com