我在下面列出了相关代码。 从本质上讲,我有2个注释,我试图自定义;
annotation1我想使用图像来表示从URL接收的位置。 annotation2将由简单的引脚表示,因为它们将用于用户在app中搜索的位置,当用户按下cancel而不影响注释1时,我还需要删除注释2
基本上,我已尝试使用IF语句,但我的应用程序一直崩溃,否则它们都由annotation1的图像表示,并且在我尝试仅删除annotation2时都被删除
以下是代表ViewController.m
中注释的代码#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize searchBar;
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
self.searchBar.delegate = self;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
- (void) dismissKeyboard
{
[self.searchBar resignFirstResponder];
[_mapView removeAnnotations:_mapView.annotations];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *identifier;
{
if (annotation == mapView.userLocation) return nil;
MKAnnotationView *annotationView;
if (annotationView == nil) {
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
annotationView.image = [UIImage imageNamed:@"bullet_red.png"];
} else {
annotationView.annotation = annotation;
}
return annotationView;
}
return nil;
}
以下是ViewController.m中的代码,它是annotation1和annotation2的源代码,它可能不相关,但以防万一
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:self.searchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
MKCoordinateRegion region;
CLLocationCoordinate2D newLocation = [placemark.location coordinate];
region.center = [(CLCircularRegion *)placemark.region center];
MKPointAnnotation *mapAnnotation = [[MKPointAnnotation alloc] init];
[mapAnnotation setCoordinate:newLocation];
[mapAnnotation setTitle:self.searchBar.text];
[self.mapView addAnnotation:mapAnnotation];
MKMapRect mr = [self.mapView visibleMapRect];
MKMapPoint pt = MKMapPointForCoordinate([mapAnnotation coordinate]);
mr.origin.x = pt.x - mr.size.width * 0.5;
mr.origin.y = pt.y - mr.size.height *0.25;
[self.mapView setVisibleMapRect:mr animated:YES];
}];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableArray *_locations = [[NSMutableArray alloc] init];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
CLLocationCoordinate2D coordinate;
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
MKPointAnnotation* marker = [[MKPointAnnotation alloc] init];
coordinate.latitude = [jsonElement [@"Latitude"] doubleValue];
coordinate.longitude = [jsonElement [@"Longitude"] doubleValue];
marker.coordinate = coordinate;
[_locations addObject:marker];
}
[self.mapView addAnnotations:_locations];
}