API 101: Get started with Google Maps API (6)

— Juliet Edjere

In this module, we'll consider Maps API use cases, particularly Google Maps, and available parameters.

At this point, we’re familiar with APIs in general.

If your app requires a geolocation function, you’ll have a number of APIs to choose from. However, most websites that have an integrated map use Google Maps APIs.

Whether you need users to create itineraries on your travel site or need to show driver routes on your delivery or ride-sharing service, Google Maps API is a good starting point. At 28,500 map loads per month for no charge, you can embed Google Maps into mobile apps and web pages, or retrieve data from Google Maps.

Google Maps features the core APIs that display customizable static or interactive maps. The Google Maps Platform offers multiple APIs for different services that provide its users with directions or points of interest.

The Platform features an API picker for help in finding the right API based on your functional requirements. The picker details a list of the most common use cases.

Google Web APIs

Google Web Service APIs

  • Directions API. Directions between multiple locations. Google’s Directions API uses an HTTP request to return XML or JSON-formatted directions between geolocations.
  • Distance Matrix API. Travel time and distance for multiple destinations.
  • Elevation API. Elevation data for any point in the world.
  • Geocoding API. Convert between addresses and geographic coordinates. It offers a REST interface that can respond in JSON and XML formats.
  • Geolocation API. Location data from cell towers and WiFi nodes. Through geolocation and multiple data layers, you can communicate with the Maps API when plotting travel routes or tracking items on the move.
  • Places API. Up-to-date information about millions of locations.
  • Roads API. Snap-to-road functionality to accurately trace GPS breadcrumbs.
  • Time Zone API. Time zone data for anywhere in the world.

Get started with Google Maps

To get started with Google Maps Platform:

  • On the Google Maps Platform homepage, click Get Started.
  • Sign in or create a Google account. Sign up for a Google Cloud Platform Free Trial.
  • Complete the verification by entering your phone number
  • Choose your Account type and complete your setup.

The URL parameters follow one of the following map actions, depending on the action requested:

  • Search — launch a Google Map that displays a pin for a specific place, or perform a general search and launch a map to display the results: https://www.google.com/maps/search/?api=1&parameters
  • Directions — request directions and launch Google Maps with the results: https://www.google.com/maps/dir/?api=1&parameters
  • Display a map — launch Google Maps with no markers or directions: https://www.google.com/maps/@?api=1&map_action=map&parameters
  • Display a Street View panorama — launch an interactive panorama image: https://www.google.com/maps/@?api=1&map_action=pano&parameters

Generate an API Key for Google Maps Static API

Getting the Google Maps API key is free. The API key identifies the client application making the request and grants or denies requests based on the client’s access permissions.

Let's consider containing the URL of a Maps Static API image of downtown New York City.

You must include an API key with every Maps API request, with at least one API key associated with your project: &key=AIzaS...3cB3cVo.

Before you get an API Key, you need an active Google Maps Platform project or create a new project to create credentials. In the Google Cloud Console, click Create Project to begin creating a new Cloud project.

A project is a basis for managing services, credentials, billing, APIs, and SDKs.

You must have the resourcemanager.projects.create permission to create a project using the Cloud Console. Go to the Manage resources page in the Cloud Console → Select organization → Create Project.

Alternatively, you can create a new project using the gcloud command-line tool, or the [projects.create()](<https://cloud.google.com/resource-manager/reference/rest/v3/projects/create>) method.

To create an API key: Click the project drop-down and select or create the project for which you want to add an API key.

Go to the Credentials page → Click Create credentialsAPI key. The new API key is listed on the Credentials page under API keys. You must enable the APIs or SDKs you plan to use with your project.

The Credentials page shows the credentials you have created, either API keys, OAuth client IDs, and/or service account keys. A digital signature, in addition to an API key, may also be required to authenticate requests. Google recommends using both an API key and a digital signature for a higher degree of security.

By setting this up, Google can track the number of requests made for usage and billing purposes.

Restrict your Google Maps Platform API key

In order to prevent your account from unwanted and malicious usage, Google recommends restricting your Google Maps Platform API key before using it in production. This ensures that only authorized requests are made with your API key.

To restrict the usage of your key:

  • First, select the right project → Open the Credentials page
  • Edit the keys that don't have a restriction by clicking the pencil icon to the right.
  • You can either restrict usage of your key to a specific application (IP address, referrer URLs, Android app, iOs app) or restrict usage of your key to one or more specific APIs.
  • To create an Application Restriction, select an option under Application restrictions and specify your application. To create an API restriction, select Restrict key under API restrictions and select one or more APIs.
  • Click Save to apply your restriction.

For example, to restrict API access to your website, go to the Credentials page → API key property page → select HTTP referrers (web sites) from the list of Application restrictions → Specify one or more referrer websites.

To restrict API access to your Shopify store, for example, enter any domain associated with your store, including your .myshopify.com domain. If you have a custom domain, then enter both https://myCustomDomain.com/ and https://shop1.myshopify.com/.

Once your key has been restricted you'll be able to block anonymous unwanted traffic, control the number of calls to your API, and identify usage patterns in your API's traffic.

Embed a Google Maps image on your web page with Maps Static API URLs

There are a number of ways to incorporate maps into your site. The Maps Static API lets you embed a Google Maps image on your web page without requiring JavaScript or any dynamic page loading.

To use the Maps Static API you must have an API key. Use the API key in your application by passing it with the key=API_KEY parameter. For API restrictions → Click Restrict key → Select Maps Static API from the Select APIs dropdown.

A Maps Static API URL must be of the following form:

The Maps Static API defines map images using the following URL parameters:

  1. Location parameters

  2. center (required if markers are not present) defines the centre of the map, equidistant from all edges of the map.

  3. zoom (required if markers are not present) defines the zoom level of the map, which determines the magnification level of the map.

  4. Map parameters

  5. size (required) defines the rectangular dimensions of the map image in a string of the form *{horizontal_value}*x*{vertical_value}*.

  6. scale affects the number of pixels that are returned. Accepted values are 1 and 2.

  7. format defines the format of the resulting image, including GIF, JPEG, and PNG types.

  8. maptype defines the type of map to construct, including roadmap, satellite, hybrid, and terrain.

  9. language defines the language to use for the display of labels on map tiles.

  10. region defines the appropriate borders to display, based on geo-political sensitivities.

  11. Feature parameters

  • markers define one or more markers to attach to the image at specified locations.
  • path defines a single path of two or more connected points to overlay on the image at specified locations, separated by the pipe character (|), or an encoded polyline using the enc: prefix within the location declaration of the path.
  • visible specifies one or more locations that should remain visible on the map, though no markers or other indicators will be displayed.
  • style defines a custom style to alter the presentation of a specific feature (roads, parks, and other features) of the map.
  1. Key and signature parameters
  • key (required) allows you to monitor your application's API usage in the Google Cloud Console
  • signature (recommended) is a digital signature used to verify that any site generating requests using your API key is authorized to do so.

The markers and path parameters take multiple locations, separated by the pipe (|) character. This is encoded as %7C in the final URL. The parameter takes a set of value assignments (marker descriptors) of the following format:

markers=*markerStyles*|*markerLocation1*| *markerLocation2*|... etc.

The following code generates a Maps Static API for Brooklyn Bridge, New York. Copy this code and embed it on your web page. Replace YOUR_API_KEY with your API key.

For this request, we specified the following parameters to construct the URL:

  • location of the map= Brooklyn Bridge, New York
  • size of the image= 600 pixels wide x 300 pixels high
  • zoom level = 13
  • type of map = roadmap
  • placement of markers with three sets of styles and three locations on the map labelled using single uppercase alphanumeric characters.
  • color= blue; label= S; at {latitude,longitude}= 40.702147, -74.015794
  • color= green; label= G; at {latitude,longitude}= 40.711614,-74.012318
  • color= red; label= C; at {latitude,longitude}= 40.718217,-73.998284
  • API Key

The latitude/longitude coordinates are defined using numerals within a comma-separated text string.

In place of the latitude/longitude values, you may instead specify a string indicating addresses. The string address parameters (e.g. "Brooklyn Bridge, New York, NY"), like latitude/longitude coordinates (e.g. "40.702147, -74.015794"), are defined by comma-separated values.

The string address is URL-encoded, so "Brooklyn Bridge, New York, NY" is converted to "Brooklyn+Bridge,New+York,NY".

The request returns the map as an image (either GIF, PNG or JPEG) you can display on your web page:

The Maps Static API creates a map based on URL parameters sent through a standard HTTP request.

Customize Maps Static API with JSON styling

You can customize the presentation of the standard Google map with the style parameters. Maps customization enables you to easily create, style, edit, and publish your maps within the Cloud Console.

You can apply your own styles to emphasize particular content, change the visual display of features such as roads, parks, built-up areas, and other points of interest, complement surrounding content on the page, or even hide features completely.

To create a customized styled map, include style parameters in the request URL. Separate parameters using the ampersand (&) character.

This code uses styling operations and simplifications to approximate the look of a US road atlas:

https://maps.googleapis.com/maps/api/staticmap?size=512x512&zoom=12&center=Chicago&format=png&style=feature:road.highway%7Celement:geometry%7Cvisibility:simplified%7Ccolor:0xc280e9&style=feature:transit.line%7Cvisibility:simplified%7Ccolor:0xbababa&style=feature:road.highway%7Celement:labels.text.stroke%7Cvisibility:on%7Ccolor:0xb06eba&style=feature:road.highway%7Celement:labels.text.fill%7Cvisibility:on%7Ccolor:0xffffff&key=YOUR_API_KEY

The API applies the rules in the order in which they appear in the style declaration in the format. Each operation is defined as a separate entry in the style array:

style=feature:*myFeatureArgument*|element:*myElementArgument*|*myRule1*:*myRule1Argument*|*myRule2*:*myRule2Argument*

Alongside the URL parameters defined in the previous section, the request URL above has the following style parameters:

  • feature to include on the map, like roads, parks, bodies of water, businesses, or other points of interest.

In this case, style=feature:road.highway highlights highways in color:0xc280e9. This feature contains child features specified using a dot notation. The style=feature:transit.line selects transit lines in color:0xbababa.

  • element of a feature, such as geometry or labels.

Here, the element:geometry selects all geometric elements of the specified highways in Chicago.element:labels.text.fill selects only the fill of the label, typically rendered as a coloured outline that surrounds the label text.element:labels.text.stroke selects only the stroke of the label's text.

  • Style rules apply to the features and elements specified within each style declaration.

color:0xffffff applies a colour to the roads, visibility:simplified simplifies the display of the roads, so they have thinner lines without outlines.

Response for Chicago highway request:

The API lets you add relevant content that is useful to your visitors and customize the look and feel of the map to fit with the style of your site.

Add a map to a web page with Maps Embed API

With Google Maps API, we can customize your own data and imagery using Maps JavaScript API, or add a map to a web page via a simple HTTP request consisting of just a URL and parameters using Maps Embed API.

The Maps Embed API lets you place an interactive map, or Street View panorama on your web page with a simple HTTP request without JavaScript. This is useful in places where you can't add <script> tags.

Similar to all APIs, the Google Maps Embed API requires an API key to embed a map on your site.

Enable the Maps Embed API to use with your project:

To load the Maps Embed API, use the URL:

Replace:

  • MAP_MODE with your map mode. You can specify [place](<https://developers.google.com/maps/documentation/embed/embedding-map#place_mode>) to display a map pin at a particular place or address, [view](<https://developers.google.com/maps/documentation/embed/embedding-map#view_mode>) to return a map with no markers or directions, [directions](<https://developers.google.com/maps/documentation/embed/embedding-map#directions_mode>) to display the path between two or more specified points on the map, [streetview](<https://developers.google.com/maps/documentation/embed/embedding-map#street_view_mode>)to show interactive panoramic views from designated locations, or [search](<https://developers.google.com/maps/documentation/embed/embedding-map#search_mode>) to show results for a search across the visible map region.
  • YOUR_API_KEY with your API key.
  • PARAMETERS with the required and optional parameters for your map mode. Maps API accommodates a host of parameters to fit your use case.

To use the Maps Embed API, first use an automatic iframe generator to embed a map into your webpage:

Unlike Maps Static API, Maps Embed API uses place IDs instead of supplying a place name or address. As London, UK is highlighted with the prefixq=place_id: is populated automatically. The following code specifies highlighting London UK: origin=place_id:ChIJdd4hrwug2EcRmSrV3Vo6llI.

The Maps Embed API accepts place IDs for the following URL parameters:q, origin, destination, and waypoints.

To test your iframe, preview the iframe in an HTML browser window:

  1. Open your default text editor - TextEdit (Mac) or Microsoft Windows Notepad (Windows).
  2. Create an HTML file and name it index.html.

Copy and paste this code with the iframe you generated above into your website's HTML. Replace the API_KEYwith your API key:

  1. Save your index.html HTML file.
  2. Load the HTML file in a web browser by dragging it from your desktop onto your browser; alternatively, double-clicking the file works on most operating systems.

The response:

Use the Maps Embed API on your web page to set the URL for City Hall, New York as the value of the src attribute of an iframe:

You can replace the map mode and parameters as well as the API key.

The iframe sample above uses the properties:

  • The height and width attributes control the map's size with the iframe
  • The allowfullscreen property allows certain map parts to go full screen.
  • The frameborder="0" and style="border:0" properties remove the standard iframe border from around the map.

In this module, we've covered a few use cases with Google Maps API. The options are wide depending on what you may want to do on a map or with location-based data. A great place to start will be the Google API picker.

In the next module, we will cover travel and booking APIs.

📎 PREVIOUS MODULE - Using Weather APIs in Postman

📎 NEXT MODULE - Defining your travel and booking with APIs


ABOUT ME

I'm Juliet 'Hiri' Edjere, a no-code expert focused on design, business development, and building scalable solutions with minimal coding knowledge.

I document all things product stories, MVP validation, and how designs, data, and market trends connect to one another.

In our world where innovation knows no boundaries, and creativity reigns supreme, no-code is a game-changer in today's tech landscape. Whether you're a developer looking to expand your skill set or a beginner curious about creating without writing a single line of code, you will learn from practical examples, and explore the possibilities of no-code technology. Together, we'll navigate the tools, platforms, and strategies – one blog post at a time!

Visit my website →

Powered By Swish