Optimization Guide  |  Google Maps Platform  |  Google for Developers (2024)

This guide describes several strategies to optimize your Google Maps APIsusage in terms of security, performance, and consumption.

Security

Reviewing security best practices

API keys are project-centric credentials that deserve the same precautionsas user IDs and passwords. Review theAPI Security Best Practices to secure your keys fromunintended use which could lead to undue quota usage and unexpected chargesto your account.

Using API keys to access Maps APIs

API keys are the preferred authentication method for accessing Google Maps APIsAPIs. While using the client IDs is currently still supported, API keyssupport finer-grained security controls and can be tuned to work with specificweb addresses, IP addresses, and mobile SDKs (Android and iOS). For informationon creating and securing an API key, go to the "Using an API Key" page for eachAPI or SDK. (For example, for the Maps JavaScript API, visitit* page on Using an API Key.)

Performance

Using exponential backoff to handle errors

If your apps experience errors from excessive attempts to call an APIwithin a short period of time, such as QPS errors, consider usingexponential backoff to let the requests process.

Exponential backoff is most useful for errors in the 500s. For more information,see Handling HTTP return status codes.

Specifically, adjust the pace of your queries. In your code, adda waiting period of S seconds between queries. If the query still resultsin a QPS error, double the waiting period and then send another query. Continueadjusting the waiting period until the query returns without an error.

Sending user-interaction requests on demand

Requests to APIs that include user interaction should be sent only on demand.This means waiting for the end user to perform an action (such as on-click)to initiate the API request, then using the results to load a map, set adestination, or display appropriate information. Using an on-demand approachavoids unnecessary requests to the APIs, reducing API consumption.

Avoiding displaying overlay content when a map is moving

Avoid using Draw() to display custom overlay content on a map at the sametime that a user might be moving the map. Since the map is redrawn every timea user moves the map, placing overlay content on the map at the same time canintroduce lag or visual stuttering. Only add or remove overlay content from amap once the user stops panning or zooming.

Avoiding intensive operations in Draw methods

As a general rule, it is good practice to avoid performance-intensivenon-drawing operations in a Draw() method. For example, avoidthe following in your Draw() method code:

  • Queries that return a large amount of content.
  • Many changes to the data being displayed.
  • Manipulating many Document Object Model (DOM) elements.

These operations can slow performance and introduce lag or visual stutteringwhen the map renders.

Using raster images for markers

Use raster images, such as images in .PNG or .JPG format, when addingmarkers to identify a location on a map. Avoid using Scalable VectorGraphics (SVG) images, since rendering SVG images can introduce lag whenthe map is redrawn.

Optimizing markers

Optimization enhances performance by rendering many markers as a single staticelement. This is useful in cases where a large number of markers is required.By default, the Maps JavaScript API will decide whether a markerwill be optimized. When there is a large number of markers, theMaps JavaScript API will attempt to render markers withoptimization. Not all Markers can be optimized; in some situations, theMaps JavaScript API may need to render Markers withoutoptimization. Disable optimized rendering for animated GIFs or PNGs, or wheneach marker must be rendered as a separate DOM element.

Creating clusters to manage marker display

To help manage the display of markers to identify locations on a map,create a marker cluster using theMarker Clusterer library.The Marker Clusterer library includes options for:

  • Grid size, to specify the number of markers to group togetherin a cluster.
  • Maximum zoom, to specify the maximum zoom level in whichto display the cluster.
  • Image paths, for the graphics images to use as marker icons.

Consumption

To plan your budget and control your costs, do the following:

  • Set a budget alert to track how your costs are growing toward a particular amount. Setting a budgetdoes not cap API usage - it only alerts you when your costs get close to yourspecified amount.
  • Cap your daily API usage to manage your costs for billable APIs. By setting caps on requests perday, you can limit your costs. Use a simple equation to determine your dailycap, depending on how much you want to spend: (monthlycost/price per each)/30 = requests per day cap (for one API). Your specific implementation mayuse multiple billable APIs, so adjust the equation as needed. A$200 USD Google Maps APIs creditis available each month, so factor that into your calculations.
  • Use multiple projects to isolate, prioritize, and track your usage.For example, suppose you regularly use the Google Maps Platform APIs in yourtests. By creating a separate project for your testing - with its own quotas andAPI keys - you can thoroughly test while guarding against surpriseover-spending.

Managing consumption in Maps

Using a single map per page is a good way to optimize maps display, sinceusers generally interact with only one map at a time. Your app can manipulatethe map to display different data sets, depending on customer interactionand needs.

Using static images

Requests that use dynamic imagery (Dynamic Maps and Dynamic Street View) costmore than Static Maps and Static Street View. If you don’t foresee userinteraction with Map or Street View (zooming or panning), use the staticversions of these APIs.

Thumbnails - very small maps and photos - are another good use for StaticMaps and Static Street View. These items are billed at a lower rate and uponuser interaction (on-click), and can take users to a dynamic version for a fullGoogle Maps experience.

Using the Maps Embed API

You can use the Maps Embed API to add a map with asingle marker, or a dynamic map, free of charge. Use theMaps Embed API for applications where a singlemarker and no map customization is required.Maps Embed API requests utilizing Directions mode,View mode, or Search mode will be billed (see thepricing table for details).

Using mobile maps SDKs for mobile applications

For mobile applications, use Maps SDK for Android orMaps SDK for iOS when displaying a map. Use the Maps Static APIor Maps JavaScript API when requirements rule outusing the mobile SDKs.

Managing consumption in Routes

Limiting Directions API waypoints

When possible, limit user entries in a query to a maximum of 10 waypoints.Requests containing more than 10 waypoints are billed at a higher rate.

Using Directions API optimization for optimal routing

Requests using the waypoint optimization argument are billed at a higher rate.For more information, see Optimize Waypoints.

The optimization argument sorts waypoints to ensure optimal routing,meaning that travel from A to E is a better experience when optimized(A-B-C-D-E) versus the random sequence of a non-optimized route(such as A-D-B-C-E).

Using real-time traffic models in Directions API and Distance Matrix API

Directions API and Distance Matrix APIrequests that include real-time traffic models are billed at a higher rate.Real-time traffic models are enabled by setting the departure time to now.

If traffic models are omitted from a request, the results are basedsolely on physical factors: roads, distance, and speed limits.

Using Route Traveled & Nearest Road when GPS data is imprecise

The Maps Roads API features, Route Traveled andNearest Road, are included in the advanced tier and are billed at a higherrate. Use these features where GPS data is imprecise and theRoads API can help determine the correct road. SpeedLimits, another feature of the Roads API, isavailable only to Asset Tracking customers.

Sampling speed limit locations at 5- to 15-minute intervals

To minimize the volume of calls to the Maps Roads APISpeed Limit service, sample the locations of your assets at 5 to 15 minuteintervals. The exact value depends on the speed at which an asset istraveling. If an asset is stationary, a single location sample issufficient. There is no need to make multiple calls.

To minimize overall latency, call the Speed Limit service once you haveaccumulated some data rather than calling the API every time thelocation of a mobile asset is received.

Managing consumption in Places

Optimizing Place Autocomplete implementations

To optimize the cost of using the Place Autocomplete:

  • use field masks in the JavaScript, Android, and iOS Autocomplete widgets to return only the Place Data Fields you need.

  • select billing options depends on your use case. Depending on whether your implementation uses Autcomplete sessions or not, you will be charged either Autocomplete - Per Request or Autocomplete - Per Session SKUs.

For more information and guidance on selecting the right option for your use case, see Place Autocomplete cost optimization best practices.

Returning data for specific fields in Place Details and Place Search requests

You can customize Place Details and Place Search requests to return datafor specific fields used in your application. These fields are broken intocategories: Basic, Contact, and Atmosphere. Requests that do notspecify any fields will receive data for all fields.

Billing for Place Details requests is based on the types and amountsof data requested. Requests that do not specify any fields will be billedat the full rate. For more information, see Place Details and Place Search.

Reducing costs by using the Geocoding API

If your application handles user-typed addresses, the addresses aresometimes ambiguous (incomplete, misspelled, or poorly formatted).Disambiguate addresses using Autocomplete, then use the place IDsto get the place locations.

If you have an exact address (or close to it), however, you can reducecosts by using Geocoding instead of Autocomplete. For more details,see Geocoding Addresses Best Practices.

How Google Maps Platform quotas work

All of our APIs have limits on how many calls each customer can make. Thesequotas are configured on a per-minute basis. Once you have reached the quota of callson a given API in a minute, future calls will not be accepted until the next minute.

Only successful requests and requests that cause server errors count againstquota. Requests that fail authentication do not count against quota.

Several Maps APIs have per-second enforcement in addition to the per-minute quotaenforcement. This per-second enforcement does not guarantee uniform usage overthe entire minute, nor will it prevent you from reaching your usage quota forthat minute. It does keep you from using up all of your quota in the firstsecond or two of any given minute, and protects you from service disruptionsin the event of sudden usage spike. To deal with these enforcement differences,plan your quota usage and requirements by averaging your QPM usage across QPS.

The GMP APIs that have this per-second enforcement areDirections API, Distance Matrix API,Elevation API, Geocoding API,Places API and Roads API.

Estimate your costs for any GMP API product, based on your total request volume.

Optimization Guide  |  Google Maps Platform  |  Google for Developers (2024)

References

Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5945

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.