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]; }
The map view uses the data in each overlay object to determine when the corresponding overlay view needs to appear onscreen. When an overlay moves onscreen, the map view asks its delegate to create a corresponding overlay renderer. var delegate: MKMapViewDelegate? The receiver’s delegate.
The MapBoxMapView can then be used inside any SwiftUI view hierarchy, for example inside the default ContentView.swift file that comes with any new SwiftUI project in Xcode. Upon launch, the map is loaded, then the user's location is acquired and the map flys to the latest user's position.
The map view uses the coordinate data in each annotation object to determine when the corresponding annotation view needs to appear onscreen. When an annotation moves onscreen, the map view asks its delegate to create a corresponding annotation view.
We also explored how to add annotations to add annotaitons to a Mapbox map. Now, let's focus on showing the user's location on the map. To enable this functionality, we can leverage the built in features of the Mapbox Maps SDK that enables the app to observe and respond the user's location.
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]; }
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With