Google Maps & Location Services

Hal Brooks
3 min readJan 14, 2022

Objective: Use Google Maps to display a 2D map of the users current location.

Open the CreateLocationPanel script and add the UnityEngine Networking and UI namespaces. The string variable url is assigned https://maps.googleapis.com/maps/api/staticmap?” allows access to the Google API static map, but needs additional parameters added after the “?”. For these parameters add float variables for xCoord, yCoord and zoom. These variables are public so can be seen in the inspector.

Variable assignment in inspector for Create_Location_Panel.

Also add a private string apiKey, using a SerializeField, to be able to paste the API key from Google console into the inspector, noting that the API key is not shown above for security reasons.

Variable assignment in the CreateLocationPanel script.

An IEnumerator Start() routine is used to check if location services is enabled, and if so starts location services with a max wait time of 20 seconds. If the devices location is found the the latitude is recorded in the xCoord and the longitude is recorded in the yCoord. If the app is unable find the location or times out appropriate Debug.Log messages are provided. Lastly the GetLocationRoutine() is started.

IEnumerator Start() routine used to obtain devices current location.

The GetLocationRoutine() assembles the url by adding the parameters assigned earlier. A new map variable of type UnityWebRequest is assigned through UnityWebRequestTexture.GetTexture(url). UnityWebRequest requires the UnityEngine.Networking namespace added earlier, and replaces the depreciated WWW class. The app then waits for the map.SendWebRequest() to respond, and checks for errors. The mapImage.texture is then assigned using the DownloadHandlerTexture.GetContent(map), which extracts the texture from map.

GetLocationRoutine() displays the 2D map image.

Some typical errors are Unity error: 400 bad request and 403 forbidden. The 400 error is incorrect syntax, often a space. No spaces are allowed. The 403 error is an invalid API. If everything is working you will see a blue field with Google in lower left and Map data ©2022 in lower right within the Unity editor. An Android Package (apk) build for the project must be created and run on an Android device for location services to fully function.

Google Static Maps has many parameter options. For example and address can be entered using an input field and used to look up a location. The link below is a good starting point for Google Static Maps’ features.

https://developers.google.com/maps/documentation/maps-static/start

--

--