我正在尝试查找从 selectedAnnotation 到 userLocation 的距离。我在注释 NSObject 中添加了以下代码:
-(void) setDistanceFromCurrentLocation:(CLLocation *)currentLocation{
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];
[self setDistance:[currentLocation distanceFromLocation:location2]];
}
- (NSString *)subtitle
{
NSString *myDistance = [NSString stringWithFormat:@"%1.1f from current location", distance];
return myDistance;
}
现在在 didUpdatedidUpdateToLocation 我尝试使用来自这个问题的以下逻辑:https ://stackoverflow.com/a/10881683/984248
仍然返回 0.0。我究竟做错了什么?
编辑:
所以我现在正在正确计算与当前位置的距离。但是我如何传递它以将其设置为 pin 的字幕?
这是我找到距离的方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self setCurrentLocation:newLocation];
// if not Current Location then update the currently displayed Dealer Annotation
for (int i=0; i<self.dataArray.count; i++){
NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
NSArray *array = [dataDictionary objectForKey:@"Locations"];
for (int i=0; i<array.count; i++){
NSMutableDictionary *dictionary = [array objectAtIndex:i];
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:[[dictionary objectForKey:@"Latitude"] doubleValue] longitude:[[dictionary objectForKey:@"Longitude"] doubleValue]];
[?????? setDistance:[self.currentLocation distanceFromLocation:pinLocation]];
}
}
}
这是我向地图添加图钉的方法:
for (int i=0; i<self.dataArray.count; i++){
NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
NSArray *array = [dataDictionary objectForKey:@"Locations"];
for (int i=0; i<array.count; i++){
NSMutableDictionary *dictionary = [array objectAtIndex:i];
MapAnnotation *annotation = [[MapAnnotation alloc] init];
annotation.latitude = [[dictionary objectForKey:@"Latitude"] doubleValue];
annotation.longitude = [[dictionary objectForKey:@"Longitude"] doubleValue];
CLLocationCoordinate2D coord = {.latitude =
annotation.latitude, .longitude = annotation.longitude};
MKCoordinateRegion region = {coord};
annotation.title = [dictionary objectForKey:@"Name"];
annotation.subtitle = ?????;
annotation.coordinate = region.center;
//Saving the dictionary of the pin to show contact info later
annotation.sourceDictionary = dictionary;
[mapView addAnnotation:annotation];
}
}