SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

How to Get GPS Location Information from Address String with Swift and iOS CLGeocoder

       

You can use CLGeocoder geocodeAddressString method. It will return an array of CLPlacemark objects that contain gps coords and city, location info.

        let address = "Burlington, Vermont"
        CLGeocoder().geocodeAddressString(address, completionHandler: { placemarks, error in
            if (error != nil) {
                return
            }

            if let placemark = placemarks?[0]  {
                let lat = String(format: "%.04f", (placemark.location?.coordinate.longitude ?? 0.0)!)
                let lon = String(format: "%.04f", (placemark.location?.coordinate.latitude ?? 0.0)!)
                let name = placemark.name!
                let country = placemark.country!
                let region = placemark.administrativeArea!
              print("\(lat),\(lon)\n\(name),\(region) \(country)")
            }
        })
    }

To go the other way, from GPS coords use reverGeocodeLocation method

let lat = 12.000
let lon = 34.000
if let loc = CLLocation(latitude: lat, longitude: lon) as? CLLocation {
                CLGeocoder().reverseGeocodeLocation(loc, completionHandler: { (placemarks, error) in
                    if let placemark = placemarks?[0]  {
                        let lat = String(format: "%.04f", (placemark.location?.coordinate.longitude ?? 0.0)!)
                        let lon = String(format: "%.04f", (placemark.location?.coordinate.latitude ?? 0.0)!)
                        let name = placemark.name!
                        let country = placemark.country!
                        let region = placemark.administrativeArea!
                        print("\(lat),\(lon)\n\(name),\(region) \(country)")
                    }
                })
Tagged w/ #swift #ios #apple #geocoding

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app