How to add map annotation on MKMapView?

Hey, I'm trying to add annotation to my map. How can i do this?

Here is my code:

- (void)abreMapa:(NSString *)endereco { NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [endereco stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]]; NSArray *listItems = [locationString componentsSeparatedByString:@","]; double latitude = 0.0; double longitude = 0.0; if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) { latitude = [[listItems objectAtIndex:2] doubleValue]; longitude = [[listItems objectAtIndex:3] doubleValue]; } else { //Show error } CLLocationCoordinate2D coordinate; coordinate.latitude = latitude; coordinate.longitude = longitude; myMap.region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000); [self.view addSubview:mapa]; } 

Thanks!

+7
source share
3 answers

Since MKAnnotation is a protocol, you will need to define your own class that implements the protocol. For example,

 @interface SPAnnotation : NSObject <MKAnnotation> { CLLocationCoordinate2D coordinate; } @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate; 

If you have latitude, longitude for the location you want to display:

 SPAnnotation *annotation = [[Annotation alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude)]; [myMap addAnnotation:annotation]; 
+16
source

You will also have to code the annotation class that accepts the MKAnnotation protocol. eg:.

 @interface MyMapAnnotation : NSObject <MKAnnotation> { ... } 
0
source

try it

 Pin *selected = [[Pin alloc] init]; for(i=0; i<[[newxml dataarray] count]; i++) { gapi = [newxml.dataarray objectAtIndex:i]; MKCoordinateRegion region ; // = { {0.0, 0.0 }, { 0.0, 0.0 } }; region.center. latitude = [gapi.lat floatValue]; region.center. longitude = [gapi.lng floatValue]; region.span.longitudeDelta = 0.05f; region.span.latitudeDelta = 0.05f; [self.mapview setRegion:region animated:YES]; Pin* myAnnotation1=[[Pin alloc] init]; myAnnotation1.coordinate=region.center;; myAnnotation1.title=gapi.name; myAnnotation1.itemIndex = i; myAnnotation1.subtitle=gapi.address; [self.mapview addAnnotation:myAnnotation1]; if (j == i) { selected = myAnnotation1; } if(k==123) { [self.mapview selectAnnotation:selected animated:NO]; } 

}

0
source

All Articles