I think you can do this work in two ways:
- Using the CLLocation Environment
Make sure you accept ViEWController using the CLLocationManagerDelegate methods
#import<MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate> { CLLocationCoordinate2D location; MKMapView *mapView; } @end
In ViewController.m:
@implementation GSViewController - (void)viewDidLoad { [super viewDidLoad]; mapView=[[MKMapView alloc] initWithFrame:self.view.frame]; mapView.showsUserLocation=TRUE; mapView.delegate=self; [self.view insertSubview:mapView atIndex:0]; CLLocationManager *locationManager=[[CLLocationManager alloc] init]; locationManager.delegate=self; locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters; [locationManager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ NSLog(@"new location: %@", newLocation); location=newLocation.coordinate; MKCoordinateRegion region; region.center=location; MKCoordinateSpan span; span.latitudeDelta=0.01; span.longitudeDelta=0.01; region.span=span; [mapView setRegion:region animated:TRUE]; } -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"error: %@", error.description); } @end
2. Using the same MKMapKit structure You can do this using the MKMapViewDelegate method called didUpdateUserLocation: Here you do not need CLLocaionManager, This will be done: In ViewController.h:
#import <MapKit/MapKit.h> @interface ViewController : UIViewController < MKMapViewDelegate> { CLLocationCoordinate2D location; MKMapView *mapView; } @end
and in the ViewController.m file:
@implementation GSViewController - (void)viewDidLoad { [super viewDidLoad]; mapView=[[MKMapView alloc] initWithFrame:self.view.frame]; mapView.showsUserLocation=TRUE; mapView.delegate=self; [self.view insertSubview:mapView atIndex:0]; } -(void)mapView:(MKMapView *)mapV didUpdateUserLocation:(MKUserLocation *)userLocation { NSLog(@"map new location: %f %f", userLocation.coordinate.latitude, userLocation.coordinate.longitude); location=userLocation.coordinate; MKCoordinateRegion region; region.center=location; MKCoordinateSpan span; span.latitudeDelta=0.1; span.longitudeDelta=0.1; region.span=span; [mapV setRegion:region animated:TRUE]; } @end
Shanmugaraja G
source share