Converting between an address and location coordinates natively in iOS
Getting Latitude and Longitude coordinates in an iOS app is quite easily achieved without the need of third-party solutions through the use of Apple’s CoreLocation framework. Contained within is the CLGeocoder class, allowing us to implement a method of transforming a description of a location (think an address or city name) into a tangible CLLocation object that we can use in multiple ways. The same class also supports retrieving a location description from a CLLocation object. Read below for both methods.
To convert a place descriptor (i.e. an address) into coordinates
To retrieve a set of coordinates from a description of a location, we can use CLGeocoder’s geocodeAddressString method. This method takes a string (as well as an optional region to search inside) as an argument and, along with a block completion handler, will spit out an NSArray of CLPlacemark objects of which you can extract coordinate and location information from.
In the above example, we initiate a CLGeocoder object, pass an address to it via the geocodeAddressString method, and in our completion handler we grab the last object from the returned array of placemarks and log out its latitude and longitude coordinates. These coordinates can be used to drop a pin on a map, be stored in a database, etc.
To convert coordinates (lat/long) into an address
The act of finding the address of a location using its coordinates is known as reverse-geocoding, and is supported by Apple’s geocoder class and its reverseGeocodeLocation method. This method takes a CLLocation object and extracts the necessary data from it in order to formulate an address.
We initiate the CLGeocoder object, but this time using the reverseGeocodeLocation method we pass it a CLLocation object. It again returns an NSArray of placemarks, from which we extract the first placemark. From that we take it’s addressDictionary attribute and store the address, city, state and zip of the placemark. Pretty nifty eh?
Note: Keep in mind that Apple’s geocoding service may only be used a certain amount of times per second. From the docs:
“Geocoding requests are rate-limited for each app, so making too many requests in a short period of time may cause some of the requests to fail. When the maximum rate is exceeded, the geocoder passes an error object with the value kCLErrorNetwork to your completion handler.”