Open map in a given address using MapKit and Swift

geocoding, geolocation, ios, mapkit, swift

Solution

You need to use the Geocoding service to convert an address to the corresponding geolocation.

For instance, add this function to your toolkit:

func coordinates(forAddress address: String, completion: @escaping (CLLocationCoordinate2D?) -> Void) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { 
        (placemarks, error) in
        guard error == nil else {
            print("Geocoding error: \(error!)")
            completion(nil)
            return
        }
        completion(placemarks.first?.location?.coordinate)
    }
}

and then use it like this:

coordinates(forAddress: "YOUR ADDRESS") { 
    (location) in
    guard let location = location else {
        // Handle error here.
        return
    }
    openMapForPlace(lat: location.latitude, long: location.longitude) 
}

Problem

I am having a bit of trouble understanding Apple's MapKit in Swift 3. I found an example here: How to open maps App programmatically with coordinates in swift? ``` public func openMapForPlace(lat:Double = 0, long:Double = 0, placeName:String = "") { let latitude: CLLocationDegrees = lat let longitude: CLLocationDegrees = long let regionDistance:CLLocationDistance = 100 let coordinates = CLLocationCoordinate2DMake(latitude, longitude) let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance) let options = [ MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span) ] let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) mapItem.name = placeName mapItem.openInMaps(launchOptions: options) } ``` This works absolutely swimmingly, except that I need to use an address instead of coordinates in this case. I have found methods for doing this using google maps, but I cant seem to find a specific answer for Apple Maps, if it exists, I've completed glazed over it. If anyone can help me to understand what the correct approach is, that would be amazing. I'm using: - Xcode 8.3.1 - Swift 3.1 - macOS - Targeting iOS 10+

Original source

Related problems