引脚在地图上放置时,在注释中显示地址

目前我可以在地图上放置别针。 现在我想让注解标题显示引脚被丢弃的地址。

我已经看了这个,但不能让我的工作:
将标注的标题设置为当前地址

代码在我的ViewController.m

更新。

- (void)addPinToMap:(UIGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state != UIGestureRecognizerStateBegan) return; CGPoint touchPoint = [gestureRecognizer locationInView:self.map]; CLLocationCoordinate2D touchMapCoordinate = [self.map convertPoint:touchPoint toCoordinateFromView:self.map]; CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude]; [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemark, NSError *error) { //initialize the title to "unknown" in case geocode has failed... NSString *annTitle = @"Address unknown"; //set the title if we got any placemarks... if (placemark.count > 0) { CLPlacemark *topResult = [placemark objectAtIndex:0]; annTitle = [NSString stringWithFormat:@"%@ %@ %@ %@", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare]; } //now create the annotation... MapAnnotation *toAdd = [[MapAnnotation alloc]init]; toAdd.coordinate = touchMapCoordinate; toAdd.title = annTitle; //toAdd.title = @"Title"; toAdd.subtitle = @"Subtitle"; [self.map addAnnotation:toAdd]; }]; } 

首先 ,在addPinToMap:方法中,使用currentLocation调用addressLocation ,但不会设置currentLocation 。 它声明了几行,但没有设置任何值。

所以改变:

 CLLocation *currentLocation; 

至:

 CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude]; 

其次 ,即使有这个修复,它仍然是行不通的。 注解的title不会被设置,因为reverseGeocodeLocation方法的完成处理程序块将在添加注释(块是asynchronous的 – addPinToMap:的代码不会等待它完成)之后完成。

您需要稍微更改代码,并在实际具有地理编码结果(无论成功还是失败)时,在完成块中添加注释。

reverseGeocodeLocation调用移动到addPinToMap:方法:

 CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude]; [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemark, NSError *error) { //initialize the title to "unknown" in case geocode has failed... NSString *annTitle = @"Address unknown"; //set the title if we got any placemarks... if (placemark.count > 0) { CLPlacemark *topResult = [placemark objectAtIndex:0]; annTitle = [NSString stringWithFormat:@"%@ %@ %@ %@", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare]; } //now create the annotation... MapAnnotation *toAdd = [[MapAnnotation alloc]init]; toAdd.coordinate = touchMapCoordinate; toAdd.title = annTitle; toAdd.subtitle = @"Subtitle"; [self.map addAnnotation:toAdd]; }];