Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Get city from annotation point

How do I get the city from an annotation point on the MKMapView in Swift? Thanks

var annot = MKPointAnnotation()

1 Answer

You should be able to use func reverseGeocodeLocation(_ location: CLLocation!, completionHandler completionHandler: CLGeocodeCompletionHandler!).

MKPointAnnotation has a coordinate property which is a CLLocationCoordinate2D. Convert .coordinate to a CLLocation.

var location = CLLocation.init( annot.coordinate.latitude, annot.coordinate.longitude)

Then you can call reverseGeocodeLocation. Note that this is an asynchronous method so you if you try and use the result in code outside of the CompletionHandler it will most likely fail until the ansynch request returns.

What CompletionHandler will receive is an array of CLPlaceMarks which has the locality property which is the city.

For Reference: https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKPointAnnotation_class/ https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLGeocoder_class/index.html#//apple_ref/occ/instm/CLGeocoder/reverseGeocodeLocation:completionHandler: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLPlacemark_class/#//apple_ref/occ/instp/CLPlacemark/locality

I am told that CLLocationCoordinate2D cannot be converted to CLLocation. Any ideas?

updated my answer