Best Practices Using Maps Datasets API Web Services Stay organized with collections Save and categorize content based on your preferences.
AI-generated Key Takeaways
Google Maps Platform web services offer HTTP interfaces for accessing geographic data and should be used within map applications, subject to license restrictions.
All Maps Datasets API applications necessitate authentication using OAuth tokens and require HTTPS for requests involving API keys or user data.
When constructing URLs, ensure they adhere to URI specifications by encoding special characters like spaces, quotes, and symbols to avoid errors.
Implement exponential backoff when retrying failed requests to prevent overloading Google's servers and avoid synchronizing large numbers of requests to prevent potential DDoS-like traffic.
Process web service responses dynamically using expressions to extract specific values, as the response format may vary between queries.
The Google Maps Platform web services are a collection of HTTP interfaces to Googleservices providing geographic data for your maps applications.
This guide describes some common practices useful for setting up your web service requests and processing service responses. Refer to thedeveloper’s guidefor full documentation of the Maps Datasets API.
What is a web service?
Google Maps Platform web services are an interface for requesting Maps API data fromexternal services and using the data within your Maps applications. These services aredesigned to be used in conjunction with a map, as per theLicense Restrictionsin the Google Maps Platform Terms of Service.
The Maps APIs web services use HTTP(S) requests to specific URLs, passing URL parameters and/orJSON-format POST data as arguments to the services. Generally, these services return data in theresponse body as JSON for parsingand/or processing by your application.
The following example shows the URL of aRESTGET request to thelist datasetsmethod:https://mapsplatformdatasets.googleapis.com/v1/projects/PROJECT_NUMBER_OR_ID/datasets
Include your request anOAuth token in theAuthorization header of the request.
Note: All Maps Datasets API applications require authentication.Get more information onauthentication credentials.
SSL/TLS Access
HTTPS is required for all Google Maps Platform requests that use API keys or contain userdata. Requests made over HTTP that contain sensitive data may be rejected.
Building a valid URL
You may think that a "valid" URL is self-evident, butthat's not quite the case. A URL entered within an address bar in abrowser, for example, may contain special characters (e.g."上海+中國"); the browser needs to internally translatethose characters into a different encoding before transmission.By the same token, any code that generates or accepts UTF-8 inputmight treat URLs with UTF-8 characters as "valid", but would also needto translate those characters before sending them out to a web server.This process is calledURL-encoding orpercent-encoding.
Special characters
We need to translate special characters becauseall URLs need to conform to the syntax specified by theUniformResource Identifier (URI) specification. In effect, this means that URLsmust contain only a special subset of ASCII characters: the familiaralphanumeric symbols, and some reserved characters for use as controlcharacters within URLs. This table summarizes these characters:
| Set | characters | URL usage |
|---|---|---|
| Alphanumeric | a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 | Text strings, scheme usage (http), port (8080), etc. |
| Unreserved | - _ . ~ | Text strings |
| Reserved | ! * ' ( ) ; : @ & = + $ , / ? % # [ ] | Control characters and/or Text Strings |
When building a valid URL, you must ensure that it contains only those characters shown in the table. Conforming a URL to use this set of characters generally leads to two issues, one of omission and one of substitution:
- Characters that you wish to handle exist outside of the above set. For example, characters in foreign languages such as
上海+中國need to be encoded using the above characters. By popular convention, spaces (which are not allowed within URLs) are often represented using the plus'+'character as well. - Characters exist within the above set as reserved characters, but need to be used literally. For example,
?is used within URLs to indicate the beginning of the query string; if you wish to use the string "? and the Mysterions," you'd need to encode the'?'character.
All characters to be URL-encoded are encodedusing a'%' character and a two-character hexvalue corresponding to their UTF-8 character. For example,上海+中國 in UTF-8 would be URL-encoded as%E4%B8%8A%E6%B5%B7%2B%E4%B8%AD%E5%9C%8B. Thestring? and the Mysterians would be URL-encoded as%3F+and+the+Mysterians or%3F%20and%20the%20Mysterians.
Common characters that need encoding
Some common characters that must be encoded are:
| Unsafe character | Encoded value |
|---|---|
| Space | %20 |
| " | %22 |
| < | %3C |
| > | %3E |
| # | %23 |
| % | %25 |
| | | %7C |
Converting a URL that you receive from user input is sometimestricky. For example, a user may enter an address as "5th&Main St."Generally, you should construct your URL from its parts, treatingany user input as literal characters.
Additionally, URLs are limited to 16384 characters for all Google Maps Platform web servicesand static web APIs. For most services, this character limit will seldom be approached. However,note that certain services have several parameters that may result in long URLs.
Polite Use of Google APIs
Poorly designed API clients can place more load than necessary on both the Internet andGoogle's servers. This section contains some best practices for clients of the APIs. Followingthese best practices can help you avoid your application being blocked for inadvertent abuse ofthe APIs.
Exponential Backoff
In rare cases something may go wrong serving your request; you may receive a 4XX or 5XX HTTPresponse code, or the TCP connection may simply fail somewhere between your client and Google'sserver. Often it is worthwhile re-trying the request asthe followup request may succeed when the original failed. However, it is important not to simplyloop repeatedly making requests to Google's servers. This looping behavior can overload thenetwork between your client and Google causing problems for many parties.
A better approach is to retry with increasing delays between attempts. Usually thedelay is increased by a multiplicative factor with each attempt, an approach known asExponential Backoff.
For example, consider an application that wishes to make this request tothe Time Zone API:
https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&key=YOUR_API_KEYThe following Python example shows how to make the request with exponential backoff:
importjsonimporttimeimporturllib.errorimporturllib.parseimporturllib.request# The maps_key defined below isn't a valid Google Maps API key.# You need to get your own API key.# See https://developers.google.com/maps/documentation/timezone/get-api-keyAPI_KEY="YOUR_KEY_HERE"TIMEZONE_BASE_URL="https://maps.googleapis.com/maps/api/timezone/json"deftimezone(lat,lng,timestamp):# Join the parts of the URL together into one string.params=urllib.parse.urlencode({"location":f"{lat},{lng}","timestamp":timestamp,"key":API_KEY,})url=f"{TIMEZONE_BASE_URL}?{params}"current_delay=0.1# Set the initial retry delay to 100ms.max_delay=5# Set the maximum retry delay to 5 seconds.whileTrue:try:# Get the API response.response=urllib.request.urlopen(url)excepturllib.error.URLError:pass# Fall through to the retry loop.else:# If we didn't get an IOError then parse the result.result=json.load(response)ifresult["status"]=="OK":returnresult["timeZoneId"]elifresult["status"]!="UNKNOWN_ERROR":# Many API errors cannot be fixed by a retry, e.g. INVALID_REQUEST or# ZERO_RESULTS. There is no point retrying these requests.raiseException(result["error_message"])ifcurrent_delay>max_delay:raiseException("Too many retry attempts.")print("Waiting",current_delay,"seconds before retrying.")time.sleep(current_delay)current_delay*=2# Increase the delay each time we retry.if__name__=="__main__":tz=timezone(39.6034810,-119.6822510,1331161200)print(f"Timezone:{tz}")
You should also be careful that there isn't retry code higher in the application callchain that leads to repeated requests in quick succession.
Synchronized Requests
Large numbers of synchronized requests to Google's APIs can look like a DistributedDenial of Service (DDoS) attack on Google's infrastructure, and be treated accordingly. Toavoid this, you should make sure that API requests are not synchronizedbetween clients.
For example, consider an application that displays the time in the current time zone.This application will probably set an alarm in the client operating system waking it up atthe start of the minute so that the displayed time can be updated. The application shouldnot make any API calls as part of the processing associated with that alarm.
Making API calls in response to a fixed alarm is bad as it results in the API calls beingsynchronized to the start of the minute, even between different devices, rather than beingdistributed evenly over time. A poorly designed application doing this will produce a spike oftraffic at sixty times normal levels at the start of each minute.
Instead, one possible good design is to have a second alarm set to a randomly chosen time.When this second alarm fires the application calls any APIs it needs and stores theresults. When the application wants to update its display at the start of the minute, it usespreviously stored results rather than calling the API again. With this approach, API callsare spread evenly over time. Further, the API calls do not delay rendering when the display isbeing updated.
Aside from the start of the minute, other common synchronization times you should be carefulnot to target are at the start of an hour, and the start of each day at midnight.
Processing Responses
Note: As the exact format of individual responses with aweb service request is not guaranteed (some elements may be missing or in multiple locations),you should never assume that the format returned for any given response will be the same fordifferent queries. Instead, you shouldprocess the response and selectappropriate values viaexpressions.This section discusses how to extract these values dynamically from web service responses.
The Google Maps web services provide responses which are easy tounderstand, but not exactly user friendly. When performing a query, ratherthan display a set of data, you probably want to extract a few specificvalues. Generally, you will want to parse responses from the webservice and extract only those values which interest you.
The parsing scheme you use depends on whether you are returningoutput in JSON. JSON responses, being already in the form ofJavascript objects, may be processed within Javascript itselfon the client.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-11-21 UTC.