Sophie Bernard
Sophie Bernard

Reputation: 207

Swift4 - How to set the map's region to a location

this is my wrong code, it should give you an Idea of what I wanna achieve

        let destCoordinates = CLLocationCoordinate2DMake(lat, long)
    let annonation = MKPointAnnotation()
    annonation.coordinate = destCoordinates
    clientMap.addAnnotation(annonation)
    self.clientMap.setRegion(MKCoordinateRegion(destCoordinates), animated: true)

Upvotes: 0

Views: 3123

Answers (2)

Sweeper
Sweeper

Reputation: 271380

You can't "just" set the the region to a coordinate. A map region consists not only of a coordinate (where the centre of the region is), but also a span (the width and height of that region). So saying something like "set the region of this map so that the centre is (0, 0)" makes no sense because you are missing the width and height of the region.

This means that you have to actively think about exactly how you want your region's span to be. In other words, how far zoomed in do you want your map to be?

If you want to remain at the same zoom level, for example, you could do this:

self.clientMap.setRegion(MKCoordinateRegion(center: destCoordindates, span: self.clientMap.region.span), animated: true)

But most of the time you probably want to zoom in to wherever your destCoordinates is for a good user experience. Try playing around with different values for the span, for example:

self.clientMap.setRegion(MKCoordinateRegion(center: destCoordindates, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)

Upvotes: 3

Daniel
Daniel

Reputation: 3597

You cannot simply cast coordinates to a region. A region takes coordinates as its center and a span as its dimensions. Read the documentation here.

This is the initializer:

MKCoordinateRegion(center: CLLocationCoordinate2D, span: MKCoordinateSpan)

Upvotes: 0

Related Questions