目前我可以在地图上放置别针。现在我希望注释标题显示引脚掉落的位置。
我已经看过这个但是不能让我工作:
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];
}];
}
答案 0 :(得分:2)
首先,在addPinToMap:
方法中,使用addressLocation
调用currentLocation
,但永远不会设置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];
}];