Making API Calls With Google Static Maps In A Unity Based App

Jon Jenkins
3 min readNov 9, 2021

Here I want to give a quick example of how to use the Google Static Map API with C# code to display a map based on the user’s device location.

The developer documentation can be found at:

Get Started | Maps Static API | Google Developers

The first thing we need to do is make sure the user has enabled location services and that it is initialized. The code below will take care of this:

Let’s go over the code item by item:

First thing is to check if location services is enabled on the device:

Next we need to start location services and wait while it is initializing. Here we are setting a max wait time of 20 seconds. If we hit the 20 second mark before initialization is complete we exit with a message saying initialization timed out.

Next we check if initialization failed. If so then we print a message saying unable to determine device location. If initialization did not fail then we will grab the latitude and longitude of the device and store them in local variables. Afterward we will stop location services. This is a good practice so that we don’t waste the user’s battery when location is not needed:

After we have received a latitude and longitude we will call a coroutine to get the map from Google corresponding to our location. We will use the center parameter so the map is centered on our coordinates.

The first thing we do in the method above is construct our URL string. This is taken directly from the documentation at Google:

The URL starts as the following string. We then add parameters to it:

It’s important to remember to be careful with the security of your API Key. Do not push it to a public repository or it will be readily viewable by everyone.

After constructing the URL it is time to make a web request to Google. This is done using the WWW class provided by Unity:

If the map WWW request returns an error we will print it out to the console. If the map returns an image we will store it in a local texture image.

That’s all there is to it. This procedure will start location services on a mobile device, get location, and query Google for a map image corresponding to the device’s location.

--

--

Jon Jenkins

A Unity Developer, interested in all things Unity.