Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open map in a given address using MapKit and Swift

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+
like image 783
big.nerd Avatar asked May 11 '17 14:05

big.nerd


2 Answers

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) 
}
like image 115
Paulo Mattos Avatar answered Oct 16 '22 11:10

Paulo Mattos


You need to use geoCode to get the coordinates from the address... This should work:

let geocoder = CLGeocoder()

geocoder.geocodeAddressString("ADDRESS_STRING") { (placemarks, error) in

  if error != nil {
    //Deal with error here
  } else if let placemarks = placemarks {

    if let coordinate = placemarks.first?.location?.coordinate {
       //Here's your coordinate
    } 
  }
}
like image 35
Andreza Cristina da Silva Avatar answered Oct 16 '22 11:10

Andreza Cristina da Silva