How to get an address from coordinates using MapKit?
I have this code when long press on the map it gets the coordinates:
func didLongPressMap(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
let touchPoint = sender.locationInView(self.mapView)
let touchCoordinate = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
var annotation = MKPointAnnotation()
annotation.coordinate = touchCoordinate
annotation.title = "Your position"
self.mapView.addAnnotation(annotation) //drops the pin
println("lat: \(touchCoordinate.latitude)")
var num = (touchCoordinate.latitude as NSNumber).floatValue
var formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 4
formatter.minimumFractionDigits = 4
var str = formatter.stringFromNumber(num)
println("long: \(touchCoordinate.longitude)")
var num1 = (touchCoordinate.longitude as NSNumber).floatValue
var formatter1 = NSNumberFormatter()
formatter1.maximumFractionDigits = 4
formatter1.minimumFractionDigits = 4
var str1 = formatter1.stringFromNumber(num1)
self.adressLoLa.text = "\(num),\(num1)"
}
}
and I want to print in annotation.title
the complete address (street, city, zip, country).
use this code this will resolve the issue.
For Swift 3: and Swift 4
First you need to set allowance to receive User's GPS in the
info.plist
.Set:
NSLocationWhenInUseUsageDescription
with a random String. And/or:NSLocationAlwaysUsageDescription
with a random String.Then I have set up a class to get the desired data like zip, town, country...:
Called by:
Done
Thanks @Kampai for his answer, I revised a bit so it works with
Swift 1.2
:Result:
[SubLocality: Sydney, Street: 141 Harrington Street, State: NSW, SubThoroughfare: 141, CountryCode: AU, ZIP: 2000, Thoroughfare: Harrington Street, Name: 141 Harrington Street, Country: Australia, FormattedAddressLines: ( "141 Harrington Street", "The Rocks NSW 2000", Australia ), City: The Rocks]
In didUpdateToLocation method:
SWIFT 4.0 : EDIT
MapKit
framework does provide a way to get address details from coordinates.You need to use reverse geocoding of map kit.
CLGeocoder
class is used to get the location from address and address from the location (coordinates). The methodreverseGeocodeLocation
will returns the address details from coordinates.This method accepts
CLLocation
as a parameter and returnsCLPlacemark
, which contains address dictionary.So now above method will be updated as:
Update:
Old/Deprecated answer:
Thanks to @Kampai's answer, here's a Swift 3 compatible and safer way (no forcing
!
):Don't forget
NSLocationWhenInUseUsageDescription
andNSLocationAlwaysUsageDescription
keys in Swift 3