MKMapView zoom to users location on viewDidLoad?

前端 未结 10 1686
有刺的猬
有刺的猬 2021-01-30 16:40

I\'m trying to zoom a map into the user\'s current location once the view loads, but I\'m getting the error \"** * Terminating app due to uncaught exception \'NSInvalidA

相关标签:
10条回答
  • 2021-01-30 17:40

    did you set showsUserLocation = YES? MKMapView won't update the location if it is set to NO. So make sure of that.

    It is very likely that the MKMapView object doesn't have the user location yet. To do right, you should adopt MKMapViewDelegate protocol and implement mapView:didUpdateUserLocation:

    map.delegate = self;
    
    ...
    -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation 
    {
        MKCoordinateRegion mapRegion;   
        mapRegion.center = mapView.userLocation.coordinate;
        mapRegion.span.latitudeDelta = 0.2;
        mapRegion.span.longitudeDelta = 0.2;
    
        [mapView setRegion:mapRegion animated: YES];
    }
    
    0 讨论(0)
  • 2021-01-30 17:42

    Check out the method setUserTrackingMode of MKMapView. Probably the easiest way of tracking the user's location on a MKMapView is

    [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    

    That way you also don't need to be a MKMapViewDelegate. The possible modes are:

    MKUserTrackingModeNone = 0, // the user's location is not followed
    MKUserTrackingModeFollow, // the map follows the user's location
    MKUserTrackingModeFollowWithHeading, // the map follows the user's location and heading
    
    0 讨论(0)
  • 2021-01-30 17:45

    As with Deepak's answer, except you could set the span more elegantly:

    - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
        MKCoordinateRegion mapRegion;   
        mapRegion.center = map.userLocation.coordinate;
        mapRegion.span = MKCoordinateSpanMake(0.2, 0.2);
        [map setRegion:mapRegion animated: YES];
    }
    
    0 讨论(0)
  • 2021-01-30 17:45

    ......

    MKCoordinateRegion region =mapView.region;
    
    region.center.latitude = currentLocation.latitude ;
    region.center.longitude = currentLocation.longitude;
    region.span.longitudeDelta /= 1000.0;
    region.span.latitudeDelta /= 1000.0;
    
    [mapView setRegion:region animated:YES];
    [mapView regionThatFits:region];
    
    0 讨论(0)
提交回复
热议问题