目前我可以在 map 上放置图钉。现在我希望注释标题显示引脚放置位置的地址。
我已经看过这个,但无法让我的工作:
Set annotation's title as current address
我的 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
方法的完成处理程序 block 将在添加注释后完成(该 block 是异步的 - 中的代码addPinToMap:
不会等待它完成)。
当您实际获得地理编码器结果(无论成功还是失败)时,您需要对代码进行一些更改,并在完成 block 内添加注释。
将 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];
}];
关于ios - 将图钉放在 map 上时在注释中显示地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645723/