我在mapView上有一个用户位置(蓝点)和注释.选择注释时,我将文本设置为distLabel – “距离点%4.0f m.”.用户移动时如何更新该文本标签?
didSelectAnnotationView:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude: [(MyAnnotation*)[view annotation] coordinate].latitude longitude: [(MyAnnotation*)[view annotation] coordinate].longitude]; CLLocation *userLocation = [[CLLocation alloc] initWithLatitude: self.mapView.userLocation.coordinate.latitude longitude: self.mapView.userLocation.coordinate.longitude]; CLLocationdistance distance = [pinLocation distanceFromLocation:userLocation]; [distLabel setText: [Nsstring stringWithFormat:@"distance to point %4.0f m.",distance]]; }
我知道有一个函数didUpdatetoLocation,但是如何将它与didSelectAnnotationView一起使用?
- (void)locationManager:(CLLocationManager *)manager didUpdatetoLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { //Did update to location }
解决方法
地图视图具有selectedAnnotations属性,您可以在didUpdatetoLocation方法中使用该属性来指示要从哪个注释获取距离.
(顺便说一句,如果您正在使用地图视图的userLocation,您可能希望使用地图视图的didUpdateUserLocation委托方法而不是使用CLUocationManager委托方法的didUpdatetoLocation.)
在委托方法中,您可以检查是否有任何当前选定的注释,如果是,则显示该注释的距离(否则说“未选择注释”).
您可能希望编写一个可以从didSelectAnnotationView和didUpdateUserLocation调用的公共方法,以减少代码重复.
例如:
-(void)updatedistancetoAnnotation:(id<MKAnnotation>)annotation { if (annotation == nil) { distLabel.text = @"No annotation selected"; return; } if (mapView.userLocation.location == nil) { distLabel.text = @"User location is unkNown"; return; } CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude]; CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:mapView.userLocation.coordinate.latitude longitude:mapView.userLocation.coordinate.longitude]; CLLocationdistance distance = [pinLocation distanceFromLocation:userLocation]; [distLabel setText: [Nsstring stringWithFormat:@"distance to point %4.0f m.",distance]]; } -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { if (mapView.selectedAnnotations.count == 0) //no annotation is currently selected [self updatedistancetoAnnotation:nil]; else //first object in array is currently selected annotation [self updatedistancetoAnnotation:[mapView.selectedAnnotations objectAtIndex:0]]; } - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { [self updatedistancetoAnnotation:view.annotation]; }