iosswiftiphoneapple-maps

Open Apple Maps programmatically


I want to open the Apple Maps App in my own Swift App, but I have only zipcode, city & street. I have NO Coordinates. I researched a lot, but there were only ways with using coordination information.


Solution

  • You can just pass your address information as URL parameters in the URL with which you open the maps app. Say you wanted the maps app to open centered on The White House.

    UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/?address=1600,PennsylvaniaAve.,20500")!)
    

    The Maps app opens with the ugly query string in the search field but it shows the right location. Note that the city and state are absent from the search query, it's just the street address and the zip.

    A potentially better approach, depending on your needs, would be to get the CLLocation of the address info you have using CLGeocoder.

    let geocoder = CLGeocoder()
    let str = "1600 Pennsylvania Ave. 20500" // A string of the address info you already have
    geocoder.geocodeAddressString(str) { (placemarksOptional, error) -> Void in
      if let placemarks = placemarksOptional {
        print("placemark| \(placemarks.first)")
        if let location = placemarks.first?.location {
          let query = "?ll=\(location.coordinate.latitude),\(location.coordinate.longitude)"
          let path = "http://maps.apple.com/" + query
          if let url = NSURL(string: path) {
            UIApplication.sharedApplication().openURL(url)
          } else {
            // Could not construct url. Handle error.
          }
        } else {
          // Could not get a location from the geocode request. Handle error.
        }
      } else {
        // Didn't get any placemarks. Handle error.
      }
    }