Reverse Geocoding: Unity lambda expression

Hal Brooks
3 min readMar 4, 2022


Objective: Use the longitude and latitude to find the address using Google Geocode API implemented using a lambda expression.

Previously described using Google maps and location services to get the latitude and longitude, which are stored respectively in xCoord and yCoord. Google location only works on an Android device, so does not work in Unity editor.

To test in the Unity editor, assign the xCoord and yCoord prior to starting the GetLocationRoutine().

Excerpt from IEnumerator Start() in CreateLocationPanel script.

The code below can now pulls the map for the coordinates provided within the Unity editor.

IEnmerator GetLocationRoutine() excerpt that pull map image from coordinates.

The coordinates used in this example are from Google’s Reverse Geocoding example. Shown below is the map for these coordinates.

Map for provided coordinates is displayed.

The string _url2 is used to construct a reverse geocode UnityWebRequest. To get the street address from these coordinates add the namespace System to access Func, which is Unity’s delegate class which can be used to return a value. Now set up a Func, FormatAddress, which requires a UnityWebRequest input parameter and returns a string.

url2 is used to access Google Geocode API and FormatAddress is a delegate event.

To setup up a new UnityWebRequest for the editor, a new API key is needed, called serverKey, which grants access to your IP address. The _url2 is then concatenated with the coordinates and the serverkey. When you deploy the app, make sure that the apiKey for Android is used. A UnityWebRequest, address, is defined using _url2, and the program then yields until a response is returned.

Create _url2 to send UnityWebRequest.

Next check the address.result for errors, if successful the FormatAddress delegate is defined using a lambda expression, i.e. => or go to. Everything within the {} following the => is the method. Within this lambda expression, the JSON output is converted to textResult using JsonUtility formatted with the AddressResult class, which is discussed further below. The textResult is converted to a string, formattedAddress, then split into a string[] array, splitAddress. The string lineResult is assembled with line breaks or “\n” and is returned. The locationAddress is the assigned by calling the FormatAddress method using address as the UnityWebRequest parameter.

Below we can see locationAddress displayed for this geocode test. The formatted address has been pulled from the longitude and latitude then split into separate lines, i.e. the postal format.

The AddressResult class can be found at the reference below, and provides the Geocode result format for use with JsonUtility.FromJson. Unfortunately, the implementation below uses the depreciated WWW class, nor returns the address in the desired postal format.