React Native
Geocoding
Learn geocoding and reverse geocoding.
Geocoding
Geocoding converts an address to geographic coordinates. The expo-location package offers Location.geocodeAsync. This function takes an address string and returns an array of location objects; each object has latitude and longitude fields.
The reverse operation is reverse geocoding: it converts a coordinate to an address. Location.reverseGeocodeAsync({ latitude, longitude }) returns an array of address objects; it carries fields like city, street, country. These two functions together do search and labeling in map apps. Both are asynchronous so they are awaited.
Reverse geocoding
The reverse operation is done with Location.reverseGeocodeAsync. The function takes an object: { latitude, longitude }. It returns an array of address objects; the first element is usually the most suitable address. Each address object carries fields like city, street, region, country.
Example: const addresses = await Location.reverseGeocodeAsync({ latitude: 41.0082, longitude: 28.9784 }). addresses[0].city gives the city name. This pattern turns the user's location into a readable address. For example, labels like 'Istanbul' or 'Kadikoy' are produced. For error tolerance the array can be empty; so a length check is done before taking the first element.
Exercise Get a coordinate from an address
Complete the geocodeAddress function. Call const results = await Location.geocodeAsync(address). Return the first result with return results[0].
Show example solution
const results = await Location.geocodeAsync(address);
return results[0];
Test yourself
-
Write the geocoding function
const results = await Location.____('Istanbul');
Show answer
const results = await Location.geocodeAsync('Istanbul');
-
Which function converts a coordinate to an address?
const addresses = await Location.??({ latitude, longitude })
- geocodeAsync
- decodeAsync
- addressAsync
- reverseGeocodeAsync
Show answer
reverseGeocodeAsync — reverseGeocodeAsync converts a coordinate to an address.
-
Match each function to its purpose
- geocodeAsync
- Address to coordinate
- reverseGeocodeAsync
- Coordinate to address
- getCurrentPositionAsync
- Current location
- watchPositionAsync
- Continuous tracking
Next lesson: Summary - Location