CodeBlanks Logo Icon CodeBlanks

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.

Practice 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].

Starter code

App.js
import * as Location from 'expo-location';

export async function geocodeAddress(address) {
  // convert the address to a coordinate and return the first result
}

Sample solution

App.js
const results = await Location.geocodeAsync(address);
return results[0];

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the geocoding function

Question
const results = await Location.____('Istanbul');
Answer
const results = await Location.geocodeAsync('Istanbul');

Explanation: geocodeAsync converts an address to a coordinate.

2 Which function converts a coordinate to an address?

App.js
const addresses = await Location.??({ latitude, longitude })
  • geocodeAsync
  • decodeAsync
  • addressAsync
  • reverseGeocodeAsync Correct answer

Explanation: reverseGeocodeAsync converts a coordinate to an address.

3 Match each function to its purpose

Term Meaning
geocodeAsync Address to coordinate
reverseGeocodeAsync Coordinate to address
getCurrentPositionAsync Current location
watchPositionAsync Continuous tracking

All lessons in Advanced