I'm having trouble zooming in on an annotation/pin when the MapView is loaded.
When loading the MapView, I want it to start zoomed out, and then zoom in toward the annotation/pin. The "animated" is set to "true". I'm not sure what it going wrong here.
When the map gets loaded, it briefly displays a gray screen with the pin and then the satellite map around it loads.
Thanks!
Using Swift 3
Map code:
@IBOutlet weak var mapView: MKMapView!
}
override func viewDidLoad() {
super.viewDidLoad()
let distanceSpan:CLLocationDegrees = 300
let redRocks:CLLocationCoordinate2D = CLLocationCoordinate2DMake(39.665496, -105.205438)
let redRocksPin = RedRocksPin(title: "Jerry Garcia 1/2/72", subtitle: "Red Rocks Amphitheatre", coordinate: redRocks)
mapView.addAnnotation(redRocksPin)
mapView.setRegion(MKCoordinateRegionMakeWithDistance(redRocks, distanceSpan, distanceSpan), animated: true)
Pin Class:
import MapKit
class RedRocksPin: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(title:String, subtitle:String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
}
In your class declaration make these your class variables:
let distanceSpan:CLLocationDegrees = 300
let redRocks:CLLocationCoordinate2D = CLLocationCoordinate2DMake(39.665496, -105.205438)
In ViewWillAppear, do this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animted)
view.layoutIfNeeded()
let redRocksPin = RedRocksPin(title: "Jerry Garcia 1/2/72", subtitle: "Red Rocks Amphitheatre", coordinate: redRocks)
mapView.addAnnotation(redRocksPin)
}
And then this:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
mapView.setRegion(MKCoordinateRegionMakeWithDistance(redRocks, distanceSpan, distanceSpan), animated: true)
}
So what this does is in your viewwillAppear, it will draw the mapView, so you are able to add the annotation without causing a crash, then in the viewdidappear, it will just zoom in on the annotation you added.
Not sure if this is the best way, but something to try.