Kenny L.
Kenny L.

Reputation: 95

iOS - MKMapView - Buggy Annotation

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];

Upvotes: 0

Views: 133

Answers (1)

yinkou
yinkou

Reputation: 5766

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 a locationManager asynchronously so it probably won't have a correct location immediately.

You need to set up a custom CLLocationManager and start its location update on your button press then set the the annotation in its delegate when it have found a location.

Upvotes: 1

Related Questions