Sunday, 8 September 2013

MapKit API and Add an Annotation on Map

Drag and Drop Map View




 Add CoreLocation and MapKit Frameworks



For setting Fake Location


Simulate Other Locations


For .h file

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MyLocationViewController : UIViewController <MKMapViewDelegate>

@property (nonatomic, strong) IBOutlet MKMapView *mapView;

@end


For .m file

@interface MyLocationViewController ()

@end

@implementation MyLocationViewController
@synthesize mapView;

.
.
.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.mapView.delegate = self;
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{

//a region that is 800 by 800 meters around the user’s location.

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];


// Add an annotation
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    point.coordinate = userLocation.coordinate;
    point.title = @"Where am I?";
    point.subtitle = @"I'm here!!!";
    
    [self.mapView addAnnotation:point];

}

Forward Geo-coding


Forward geocoding means you’re starting with an address and are seeking coordinates

NSString *address = @"1 Infinite Loop, CA, USA";

CLGeocoder *geocoder = [[CLGeocoder alloc] init];

[geocoder geocodeAddressString:address completionHandler:^(NSArray* placemarks, NSError* error){


// Check for returned placemarks
 if (placemarks && placemarks.count > 0) {

CLPlacemark *topResult = [placemarks objectAtIndex:0];

// Create a MLPlacemark and add it to the map view

MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
[self.mapView addAnnotation:placemark];                   
}
                 }];


Reverse Geo-coding

Reverse geocoding is the process of converting a CLLocation into a CLPlacemark. Remember that the CLPlacemark contains the CLLocation, CLRegion, and an NSDictionary for the address.


CLGeocoder *geocoder = [[CLGeocoder alloc] init];

[geocoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray *placemarks, NSError *error) {

 if(placemarks.count){
      NSDictionary *addressDict= [[placemarks objectAtIndex:0] addressDictionary];
    }
  }];











No comments:

Post a Comment