How to get the Map to zoom to currentLocation on startup



Just thought I would share this. Hopefully this will help a few folks.
First thing is that the simulator is NOT going to behave the same as running it on a device. This will ONLY work as expect running directly on a device. If you run any Map Location code in the simulator you will always get the current location to show Apple HQ in Cupertino, CA.

I’m running iOS 4.2 which is the latest as of 10/8/10 and this worked for me.

I added a method to tell the locationManager to actually start up. Unless you do this the locationManager will not start getting call backs until you fire a text change event. (This was my observation.)

[code]- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Create location manager object
locationManager = [[CLLocationManager alloc] init];

// Make this instance of WhereamiAppDelegate the delegate
// it will send its messages to our WhereamiAppDelegate
[locationManager setDelegate:self];

// We want all results from the location manager
[locationManager setDistanceFilter:kCLDistanceFilterNone];

// And we want it to be as accurate as possible
// regardless of how much time/power it takes
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

// Once configured, the location manager must be "started".
[locationManager startUpdatingLocation];

// set mapview to users current location
[_mapView setShowsUserLocation:YES];

[window makeKeyAndVisible];

return YES;


Then the only other item I had to do was tell the mapView to zoom on the first location call back event.

I achieved this by the if condition block in the following code below:

[code]- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {

NSLog(@"%@", newLocation);
NSLog(@"%@", oldLocation);    

// call this the first time only when oldLocation is Null
if (!oldLocation) {
    NSLog(@"setting location");
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 5000, 5000);
    [_mapView setRegion:region animated:YES];


Here is what the log file shows after downloading and running it on a 2nd generation iPod touch with the latest beta.

2010-10-08 14:21:13.082 Whereami[39778:307] <+35.01190494, -80.79608075> +/- 107.38m (speed -1.00 mps / course -1.00) @ 10/7/10 4:54:04 PM Eastern Daylight Time 2010-10-08 14:21:13.085 Whereami[39778:307] (null) 2010-10-08 14:21:13.087 Whereami[39778:307] setting location 2010-10-08 14:21:14.353 Whereami[39778:307] <+35.01226128, -80.79627136> +/- 65.00m (speed -1.00 mps / course -1.00) @ 10/8/10 2:21:13 PM Eastern Daylight Time 2010-10-08 14:21:14.445 Whereami[39778:307] <+35.01190494, -80.79608075> +/- 107.38m (speed -1.00 mps / course -1.00) @ 10/7/10 4:54:04 PM Eastern Daylight Time