Arno
Arno

Reputation: 471

iOS MapKit - showAnnotations to Include User Location on Zoom

I have a network call in viewDidAppear that retrieves a list of sites containing location information to be displayed on a map. When calling showAnnotations the map will zoom to show all annotations excluding the user's location.

Other Stack Overflow questions say to call showAnnotations with the animated flag as true, but this doesn't work.

// Assign new sites
self.sites = newSites

// Show annotations on map
self.mapView.showAnnotations(self.sites, animated: true)

Why does this only zoom to show sites but not the user's location?

Upvotes: 0

Views: 1001

Answers (1)

Arno
Arno

Reputation: 471

The problem is that showAnnotations will add the annotations to the map and only zoom to show those - which makes perfect sense. So how can we include the user's location? I did it with the following code:

// Assign new sites
self.sites = newSites

// Add new annotations
self.mapView.addAnnotations(self.sites)

// Show all annotations to include current user location
self.mapView.showAnnotations(self.mapView.annotations, animated: true)

The key part here is to add the annotations using mapView.addAnnotations first, then call mapView.showAnnotations(..., animated: true) on all the mapView's annotations which includes the user's location.

Upvotes: 1

Related Questions