开发者

How do I center over a specific location and then zoom to current location

开发者 https://www.devze.com 2023-04-02 07:52 出处:网络
Very much a newbie here so please forgive the ignorance.I have spent some time trying to understand what I am missing but cannot figure it out.

Very much a newbie here so please forgive the ignorance. I have spent some time trying to understand what I am missing but cannot figure it out.

My app centers over Washington State when loading but when I try to zoom to the users current location it puts me at latitude 0 longitude 0. If I comment out the "// startup: center over WA" section it centers over the users current location and then goToLocation works fine.

How do I get it to center over Washington State and then zoom to the users current location upon clicking goToLocation?

Thanks!

- (void)viewDidLoad {

    [super viewDidLoad];
    [self loadOurAnnotations];
        [mapView setShowsUserLocation:NO];

// startup: center over WA
    CLLocationCoordinate2D defaultCoordinate;
    defaultCoordinate.latitude = 47.517201;
    defaultCoordinate.longitude = -120.366211;
    [mapView setRegion:MKCoordinateRegionMake开发者_开发百科(defaultCoordinate, MKCoordinateSpanMake(6.8, 6.8)) animated:NO];


}


-(IBAction)goToLocation {
    MKUserLocation *myLocation = [mapView userLocation];
    CLLocationCoordinate2D coord = [[myLocation location] coordinate];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 350, 350);
    [mapView setRegion:region animated:YES];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1];
    [UIView commitAnimations];
}


First, to use userLocation in the MKMapView at all, you have to pass YES to setShowsUserLocation (not NO).

Next thing is that after turning showsUserLocation on, it may take a few seconds or more for the map view to determine the location and set userLocation. Until then, the location will be nil (giving coordinates of 0,0).

To really know when the userLocation is ready (or updated), implement the didUpdateUserLocation delegate method. It's also helpful to implement the didFailToLocateUserWithError method in case of a problem determining the user location.

However, in your case, you could just do the following in the goToLocation method:

MKUserLocation *myLocation = [mapView userLocation];
if (myLocation.location == nil)
{
    NSLog(@"user location has not been determined yet");
    return;
}
CLLocationCoordinate2D coord = [[myLocation location] coordinate];
MKCoordinateRegion region = ... //rest of the code stays the same

The animation statements at the end of that method don't do anything, by the way.

0

精彩评论

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

关注公众号