MKMapView zoom to users location on viewDidLoad?

前端 未结 10 1684
有刺的猬
有刺的猬 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:20

    The problem that occurs when you use the didUpdateUserLocation method, you will not be able to scroll nor zoom to another location. It will keep pointing to your location. The best way (that I've tried) is that you need to use the location manager.

    In the viewDidLoad add the following :

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLLocationAccuracyKilometer;;
    // showing user location with the blue dot
    [self.mapView setShowsUserLocation:YES];
    
    self.mapView.delegate = self;
    
    // getting user coordinates
    CLLocation *location = [_locationManager location];
    CLLocationCoordinate2D  coordinate = [location coordinate];
    
    
    // showing them in the mapView
    _mapView.region = MKCoordinateRegionMakeWithDistance(coordinate, 250, 250);
    
    [self.locationManager startUpdatingLocation];
    

    this way you could display your location with the zoom that you want. I hope this will help.

提交回复
热议问题