Integrating Google Maps API with Unity

Ali Emre Onur
4 min readJun 13, 2021

In the Insurance app, we have a map field for the user to share the accident location. To activate the map functionality, we will need to use Google Maps API. For more information how to set it up, simply follow the instructions following the link:

Once you are done, your API Key will be displayed on the screen. If somehow you cannot copy it, you can reach it by clicking on the “Credentials” from the menu on the left.

Then, select the Maps Static API from the drop down menu.

In order to download a map information, we will need to use the provided API key.

Thus, in Unity, we will need to use a variable to hold our API Key. The map will be included within the LocationPanel. Thus, we add a string variable to LocationPanel script and then copy-paste our API Key provided by Google to the inspector.

public string apiKey;

If you read the first sentence in the Maps getting started info page:

The Maps Static API returns an image (either GIF, PNG or JPEG) in response to an HTTP request via a URL.

Thus, we will create a request using a URL which includes our API. For more information, follow the following link that also includes some examples:

Once you check the link, you will realize that a map URL simply consists of:

  • X Coordinate
  • Y Coordinate
  • Zoom
  • Size
  • API Key
Here’s the sample map URL shared within the link : https://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=14&size=400x400&key=YOUR_API_KEY 

In the application, we have already created and filled the API variable. Additionally, we are going to be providing x, y coordinates along with the zoom and size.

As you might have been realized, the beginning of the URL stays the same irrelevant from the location :

https://maps.googleapis.com/maps/api/staticmap?

Thus, we will be adding the variables after this link, which will be stored as a string variable.

Gathering User Location Data

The application requires the user to share the incident location. Unity has built-in location services support. Check out Unity manual about it following the link :

First, we will need to check if the user allowed location services to be used. If enabled, we will be waiting for 20 seconds before giving a time out error. If it is not timed out or failed, we will be gathering the location data from the user.

After that, we need to communicate with Google for providing the maps position.

WWW class within Unity allows us to reach websites. Checking the Unity Manual, you will realize that it has been replaced with UnityWebRequest (click here for new Manual). Before digging into the new class, I will be implementing the old way for now.

Lastly, make sure to fill in the ProcessInfo method as this script also implements from the IPanel interface.

--

--