Arda Arda - 3 months ago 20
Swift Question

how to get location name from default annotations Mapkit in iOS

How can I get the locations' name from Mapkit's default location points in iOS.

I want to click on it(ex.Swiss Hotel) and get name in Swift

enter image description here

Answer

step-1

add gesture on your map

let tgr = UITapGestureRecognizer(target: self, action: #selector(self.tapGestureHandler))
tgr.delegate = self
mapView.addGestureRecognizer(tgr)

step-2

get the coodinates on touched places like

func tapGestureHandler(tgr: UITapGestureRecognizer)
{
let touchPoint = tgr.locationInView(yourmapview)
let touchMapCoordinate = yourmapview.convertPoint(touchPoint, toCoordinateFromView: yourmapview)
print("tapGestureHandler: touchMapCoordinate = \(touchMapCoordinate.latitude),\(touchMapCoordinate.longitude)")
}

step-3

finally convert lat and long to address

let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: touchMapCoordinate.latitude, longitude: touchMapCoordinate.longitude)

    geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placemarks?[0]

        // Address dictionary
        print(placeMark.addressDictionary)

        // Location name
        if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
            print(locationName)
        }

        // Street address
        if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
            print(street)
        }

        // City
        if let city = placeMark.addressDictionary!["City"] as? NSString {
            print(city)
        }

        // Zip code
        if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
            print(zip)
        }

        // Country
        if let country = placeMark.addressDictionary!["Country"] as? NSString {
            print(country)
        }

    })