Kevin Kevin - 15 days ago 5
Swift Question

Forward Geocoding with Swift

I am looking to be able to have a user input an address, and be able to save that address, and convert it into latitude and longitudinal coordinates. I haven't been able to find much documentation on forward geocoding, and I am having trouble starting this code. Should I ask the user to input the address by (city, state, zip code)? Or would a single address suffice? Is there a function that can do what I need? Any help is much appreciated.

Answer

I have made a simple LocationManager helper on github in which you can get the thing what you want.

There is a function getReverseGeoCodedLocation in the library. Just input your address as a String and get the complete placemark and lat, longs.

Add the LocationManager.swift file in your project

How to use it:-

LocationManager.sharedInstance.getReverseGeoCodedLocation(address: yourAddress, completionHandler: { (location:CLLocation?, placemark:CLPlacemark?, error:NSError?) in

        if error != nil {
            print((error?.localizedDescription)!)
            return
        }

        if placemark == nil {
            print("Location can't be fetched")
            return
        }

        print(placemark?.addressDictionary?.description ?? "")
        print((placemark?.location?.coordinate.latitude)!)
        print((placemark?.location?.coordinate.longitude)!)

})

Internally it uses the geocodeAddressString of CLGeocoder

Output

enter image description here Note:- It is for Swift 3.0 and above

Comments