Open Apple Maps programmatically in iOS8, Xcode 7, Swift 2

I want to open the Apple Maps app in my own Swift ios8 app, but I only have the zip code, city and street. I have no coordinates. I researched a lot, but there were only ways to use coordination information.

+5
source share
3 answers

You can simply pass your address information as URL parameters in the URL with which you open the map application. Say you want the map app to open in the center of the White House.

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

"" , . , , .

, , , CLLocation , 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.
  }
}
+14

Swift 4 Xcode 9

:

import CoreLocation

:

let geocoder = CLGeocoder()

let locationString = "London"

geocoder.geocodeAddressString(locationString) { (placemarks, error) in
    if let error = error {
        print(error.localizedDescription)
    } else {
        if let location = placemarks?.first?.location {
            let query = "?ll=\(location.coordinate.latitude),\(location.coordinate.longitude)"
            let urlString = "http://maps.apple.com/".appending(query)
            if let url = URL(string: urlString) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
}
+1

Swift 4

UIApplication.shared.open(URL(string:"http://maps.apple.com/?address=yourAddress")!)
0

Source: https://habr.com/ru/post/1616417/


All Articles