I have a button when if pressed I want it to get the users location and drop an annotation on it. But it seems that I press it once, it adds the annotation in the middle of the ocean then my users location appears (which works). I press it the second time and it adds the annotation on my location.
Code:
mapView.showsUserLocation = YES;
MKCoordinateRegion newRegion;
newRegion.center.latitude = mapView.userLocation.location.coordinate.latitude;
newRegion.center.longitude = mapView.userLocation.location.coordinate.longitude;
newRegion.span.latitudeDelta = 0.0004f;
newRegion.span.longitudeDelta = 0.0004f;
[mapView setRegion: newRegion animated: YES];
CLLocationCoordinate2D coordinate;
coordinate.latitude = mapView.userLocation.location.coordinate.latitude;
coordinate.longitude = mapView.userLocation.location.coordinate.longitude;
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate: coordinate];
[annotation setTitle: @"Your Car"];
[annotation setSubtitle: @"Come here for pepsi"];
[mapView addAnnotation: annotation];
[mapView setZoomEnabled: YES];
[mapView setScrollEnabled: YES];
It sounds like that you are asking for the userlocation before the CLLocationManager have found it.
By setting
mapView.showsUserLocation = YES;the mapview starts locating the user with alocationManagerasynchronously so it probably won’t have a correct location immediately.You need to set up a custom
CLLocationManagerand start its location update on your button press then set the the annotation in its delegate when it have found a location.