MKMapView zoom to users location on viewDidLoad?

2020-05-14 03:56发布

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 'NSInvalidArgumentException', reason: 'Invalid Region '" when the view loads. Please can someone help?

Cheers!

- (void)viewDidLoad
{
    [super viewDidLoad];

    MKCoordinateRegion mapRegion;   
    mapRegion.center.latitude = map.userLocation.coordinate.latitude;
    mapRegion.center.longitude = map.userLocation.coordinate.longitude;
    mapRegion.span.latitudeDelta = 0.2;
    mapRegion.span.longitudeDelta = 0.2;
    [map setRegion:mapRegion animated: YES];   
}

10条回答
劳资没心,怎么记你
2楼-- · 2020-05-14 04:27

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
查看更多
叛逆
3楼-- · 2020-05-14 04:29

By far the easiest way is to use mapView.showAnnotations in didUpdateUserLocation:

func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
    mapView.showAnnotations([userLocation], animated: true)
}

That's all!

MKUserLocation conforms to the MKAnnotation protocol. Pass the userLocation as an array, the showAnnotations method will let the mapView zoom in on a region plus padding spanning the array of MKAnnotations,in this case it's just the userLocation. Works for me.

If you only want to zoom in once, use a initialUserLocation property to check whether the initial property was already set. I don't like using dispatch_once at all for that sort of thing

查看更多
Animai°情兽
4楼-- · 2020-05-14 04:30

Swift 3 version Use this method to zoom into any coordinate.

extension MKMapView{
    func zoomIn(coordinate: CLLocationCoordinate2D, withLevel level:CLLocationDistance = 10000){
        let camera =
            MKMapCamera(lookingAtCenter: coordinate, fromEyeCoordinate: coordinate, eyeAltitude: level)
        self.setCamera(camera, animated: true)
    }
}
查看更多
再贱就再见
5楼-- · 2020-05-14 04:31

Check the value of map.userLocation.coordinate, the rest is OK.

查看更多
登录 后发表回答