NSXML Parsing with Rest api and Mapview with Annotation?


Hi,

Today I am going to explain you How to perform Parsing with NSXML and How to show annotation in MKMapView.

Here I am Taking 1 UITextField and 1 UIButton.Whatever city name you will enter in the Textfield and Press Button it will show you in MKMapView with Annotation.

Step 1: Add Frameworks

1.CoreLocation

2.MapKit

step 2: Add Files

1.Place.h and Place.m

2.PlaceMark.h and PlaceMark.m (I will Provide).

step 3: Import Files in your view controller’s header file  and Declare Variables as shown in the Screenshots.

step 4: @synthesize all Variables as shown.

Step 5: Take NSString with Rest api and provide the textfield value to it.Make the connection with URL Request as shown.

NSString *strUrl = [NSString stringWithFormat:@”http://maps.googleapis.com/maps/api/geocode/xml?address=%@&sensor=false”,self.txtSearch.text];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]] delegate:self];

check the connection object

if(conn)
self.data = [[NSMutableData data] init];

Step 6:Implement all the connection Methods as shown.

#pragma mark – Connection Delegates Methods

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@”Error ==>%@”,error);

}
– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.data appendData:data];

}
– (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//Standard NSXMLParser – SAX Parser
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.data];
parser.delegate=self;
[parser parse];
}
Step 7:Now Implement Parsing Methods with Root Tag and Object Tag so it will give’s you all the tags.

#pragma mark – NSXML Parsing Delegates Methods

// Document handling methods
// sent when the parser begins parsing of the document.
– (void)parserDidStartDocument:(NSXMLParser *)parser{

}
// sent when the parser finds an element start tag.
– (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:@”GeocodeResponse“])
self.arrResult = [NSMutableArray array];
else if ([elementName isEqualToString:@”result“])
self.dMain = [NSMutableDictionary dictionary];
}
– (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
self.strings=string;
}

// sent when an end tag is encountered. The various parameters are supplied as above.
// sent when the parser has completed parsing. If this is encountered, the parse was successful.
– (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:@”GeocodeResponse“]){

}else if ([elementName isEqualToString:@”result“])
{
[self.arrResult addObject:self.dMain];
self.dMain=nil;
}else {
[self.dMain setObject:self.strings forKey:elementName];
}
}

Step 7:In parserDidEndDocument method you will get all the value whatever you required.Here I am getting Latitude/Longitude and Address as shown.

=> Make the object of Place class and Provide the parameter also make the object of PlaceMark and Provide the object of place class and Add the Placemark object to MapView as an Annotation.

– (void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@”Array = %@”,self.arrResult);

float latitude= [[[self.arrResult objectAtIndex:0] valueForKey:@”lat”] floatValue];
float longitude=[[[self.arrResult objectAtIndex:0] valueForKey:@”lng”] floatValue];

Place* home = [[Place alloc] init];
home.name = [[self.arrResult objectAtIndex:0] valueForKey:@”formatted_address”];
home.latitude = latitude;
home.longitude = longitude;

PlaceMark *from = [[PlaceMark alloc] initWithPlace:home];
[self.mView addAnnotation:from];
[self centerMap];
}

Step 8:For Annotation here you have to Integrate MKMapView’s Annotation Delegate methods as shown.

#pragma mark – MapView Annotation

– (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
// if it’s the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;

// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = @”AnnotationIdentifier”;
MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
return pinView;
}

You can download the sample code From Here.

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s