开发者

Center region on userLocation in MKMapView

I'm confused. I have an MKMapView, and in the viewDidLoad method I do:

- (void)viewDidLoad {
    mainDelegate = (PublicArtOmahaAppDelegate*)[[UIApplication sharedApplication]delegate]; 

    XMLController  *myXMLController = [[XMLController alloc] init]; 
    [myXMLController parse];
    mapView.showsUserLocation = YES;
    [self gotoLocation];

    // add annotations to map
    [self.mapView addAnnotations:mainDelegate.mapAnnotations];
    [myXMLController release];
}

[self gotoLocation] calls:

- (void)gotoLocation
{
    MK开发者_JS百科CoordinateRegion newRegion;

    CLLocation *userLocation = mapView.userLocation.location;
    float latitude = userLocation.coordinate.latitude;
    float longitude = userLocation.coordinate.latitude;
    newRegion.center.latitude = latitude;
    newRegion.center.longitude = longitude;

    [self.mapView setRegion:newRegion animated:YES];
}

So I thought this should center the map on the user's location when the mapView loads and I was also planning on implementing a button on the screen that would manually call gotoLocation again to update the user's location when they want.

But... when I run the app on a device it loads the map centered in a patch of ocean west of Africa which is apparently lat and long 0,0. What I thought was strange was that when I zoomed back to my real location, it had correctly placed my location as an annotation. So I guess there's something wrong with how I'm setting the user location in the gotoLocation? Anyone notice what I'm doing wrong?


From the MKUserLocation documentation:

location

The current location of the device. (read-only)

@property (readonly, nonatomic) CLLocation *location

Discussion

This property contains nil if the map view is not currently showing the user location or if the user’s location has not yet been determined.

It takes a few seconds for the MKMapView (or CLLocationManager) to get a fix on the user's location, and it may take a couple of tries to get a relatively accurate fix. Your best bet is probably to create a CLLocationManager object, assign it a delegate, and then zoom the map when the locationManager:didUpdateToLocation:fromLocation: method fires.


You should set the span for the region too. Set it to some arbitary value, like latitudeDelta = 0.01 (and the same for latitudeDelta).

Also, call gotoLocation from inside – locationManager:didUpdateToLocation:fromLocation: (if you're using a location manager). That way you'll only call it when you have a valid user location.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜