目前我可以在地图上放置图钉。 现在,我希望注释标题显示引脚放置位置的地址。
我已经看过这个,但无法让我的工作:
将批注的标题设置为当前地址
我的视图控制器中的代码.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
方法的完成处理程序块将在添加注释后完成(块是异步的 - 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];
}];