Search This Blog

Jul 13, 2010

How to show current location and set zoom level on MapKit.

This example shows how to show google map on iPhone and set zoom level on it. This example also use iPhone CLLocationManager for showing your current location using GPS of iPhone device.


You can download source code from here Download.

Code for .h file.

#import
#import
#import

@interface UIShowMapViewController : UIViewController {

    IBOutlet MKMapView *mapView;
    CLLocationCoordinate2D theCoordinate;
    CLLocationManager *currentLocation;
}

@property (nonatomic,retain)MKMapView *mapView;

- (void)showAnnotation;

@end

Code for .m file.

#import "UIShowMapViewController.h"
#import "DDAnnotation.h"

@implementation UIShowMapViewController
@synthesize mapView;

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.title = @"Google Map";
  
    currentLocation = [[CLLocationManager alloc]init];
    currentLocation.desiredAccuracy = kCLLocationAccuracyBest;
    currentLocation.delegate = self;
    [currentLocation startUpdatingLocation];
}

- (void)showAnnotation
{
    //theCoordinate.latitude = 26.926;
    //theCoordinate.longitude = 75.8235;
    MKCoordinateRegion region;
    region.center = theCoordinate;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    region.span=span;
    [mapView setRegion:region animated:TRUE];
  
    DDAnnotation *annotation = [[[DDAnnotation alloc] initWithCoordinate:theCoordinate addressDictionary:nil] autorelease];
    annotation.title = @"Drag to Move Pin";
    annotation.subtitle = @"Tripolia Bazar, Biseswarji, Pink City, Jaipur, Rajasthan, India";
  
    [self.mapView addAnnotation:annotation];
}

#pragma mark Location Manager Event

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{  
    [currentLocation stopUpdatingLocation];  
    theCoordinate.latitude = newLocation.coordinate.latitude;
    theCoordinate.longitude = newLocation.coordinate.longitude;
    [self showAnnotation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{  
    [currentLocation stopUpdatingLocation];
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
   
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
 

5 comments:

  1. very useful, thanks for sharing..

    ReplyDelete
  2. How can we get the locality name ? I have used annotation.locality.... but it doesnt show :(

    ReplyDelete
    Replies
    1. By using "placemark" u can find location name

      Delete
    2. By using "placemark" using this u can find the location name like city,state,pincode ...etc

      Delete