Google is committed to advancing racial equity for Black communities. See how.

Best Practices Guide: Google Maps Platform retail solutions

From researching goods online to choosing the nearest store for pickup and simplifying the checkout flow, Google Maps Platform provides functionality that can help retailers drive online to offline sales and improve customer experiences.

This document focuses on the best practices in two solutions:

  1. Store Locator Plus: enabling a customer to find and navigate to your store.
  2. Checkout: helping your customers speed through their checkout process with predictive address entry.

Store Locator Plus

Since the launch of Google Maps Platform, businesses have used the services to allow customers to find their nearest stores or restaurants. Store Locator Plus is what we recommend as the optimal combination of APIs that customers can build this service. The tips below highlight the elements that are essential for an enhanced store locator implementation.

Store Locator Plus consists of the following components:

Maps JavaScript API
Build customized, agile experiences that bring the real world to your users with static and dynamic maps, Street View imagery, and 360° views.
Place Autocomplete
Add type-as-you-go functionality to improve the user experience on all platforms and improve address accuracy with minimum keystrokes.
Geocoding API
Get basic location information from an address entry to allow customers to find the best route to store locations.
Distance Matrix API
Calculate the travel distance and travel time for multiple origins and destinations, optionally specifying various forms of transport: walking, driving, cycling.
Directions API
Get directions data from origin to destination using various forms of transport: walking, driving, cycling, public transit.
Place Details
Get the name, address, opening hours, and other details of a store or restaurant, including customer ratings and reviews.
Street View
Display a static Street View panorama.
Static Map
Display a fixed image of a map, and optionally add markers, polygons, rectangles, polylines, circles and customized styling. This is useful, for example, if you don't need an interactive map and want to optimize performance and size.

Drive traffic to your stores: Maps APIs and SDKs

A store locator is an important part of the retail experience. Some sites, however, may lack even a simple map, requiring customers to leave the site or the app to see where a nearby store or product is located. This means a suboptimal experience for customers who must navigate between pages in order to get the information they require. Instead, you can enhance this experience by embedding and customizing maps into your applications.

Add your map into any application

Google Maps Platform is available for Android, iOS, and web. All of these services allow you to embed maps within your application on each platform and place markers on top of the maps showing the location of any store or pickup points.

Customize your map

You can customize your markers by changing the default color (possibly showing whether a store is currently open) or replacing the marker with a custom image, such as the logo of your brand. Info windows, or pop-up windows, can provide additional information to the customer, such as opening hours, phone number, or even photos.

Maps can also be modified in order to match the look and feel of the rest of your site. With the new online style editor, you can create cloud-based styles tailored to your branding that can be used in both web and mobile applications and be deployed with no code changes.

Getting Started with the Maps JavaScript API

Adding a map to your page can be done with a few lines of code. First, you need to include the Maps API in the page. This is done through linking the script below in your HTML page.

<script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&region=JP"></script>

Next you will need a location to place your map on the page. This is the place where the map will be created.

<div id="map"></div>

This specific line references the initMap script which is run when the page loads and runs the code you use to set up the map in the page. This link can also be used to define the language or region of your map to make sure it’s formatted in the correct way for the specific country you are targeting. View the Google Maps Platform Coverage Details for a full list of supported languages and regions.

The next step is to set the basic functionality of your map. This is done in the initMap script function specified above. In this script, you can set the initial location, the type of map and which controls will be available on the map for your users. An example of this is below:

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -33, lng: 151 }, zoom: 8,
    zoomControl: false
  });
}

For a store locator, you're usually interested in setting the initial location, the center point or bounds and the zoom level (how much the map is zoomed into that location). Most other elements, such as turning of controls, are optional as you determine the level of interaction with the map.

The next step is to add your locations to the map. This is usually done by adding markers to the map, although there are a number of other options that can be used such as data layers. An example of adding a marker is shown below:

var marker = new google.maps.Marker({
    position: { lat: 52.6, lng: -1.68 },
    label:"A",
    title:"Store Name"
});

// To add the marker to the map, call setMap();
marker.setMap(map);

With a few markers, you can see the location of a number of stores together.

Once you have a map and locations in place, there are a number of other elements that might be integrated in order to complete the look and feel of the map to fit into your branding. You can use the style editor to create a style that might align with the rest of your site to emphasize your locations in relation to the background details.

Learn more about the online style editor. Once you have the style created and published, you can then reference this in your map through the use of the mapId.

map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: -33, lng: 151},
  zoom: 4,
  mapId: 'MAP_ID'
});

Any map style you create can be edited at any time. The new look will automatically update the existing application and be used across platforms.

Identify your customer’s location: Place Autocomplete

The next key component in any store locator is identifying the location of your customer. This can be done in a number of ways automatically, using the location functions built into browsers or mobile devices. Capturing the customer's address in a simple manner, however, is not an easy task, especially on mobile devices.

Today's users are accustomed to the autocomplete type-ahead functionality on the consumer version of Google Maps. This functionality can be integrated into any application using the Places Libraries on mobile devices and the web. When a user types an address, autocomplete will fill in the rest either through the use of widgets on each device or you can deploy your own using the SDKs or web services directly.

Getting Started with Place Autocomplete

It only takes a couple of lines of JavaScript code to incorporate Place Autocomplete into your site.

First, you need to include the Maps JavaScript API in your site and specify the Places library as shown below, which also executes the initialization function.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" defer></script>

Next, add a text box to your page, for user input.

<input id="autocomplete" placeholder="Enter your address" type="text"></input>

Finally you need to initialize the Autocomplete service and link it to the named text box:

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -33, lng: 151 }, zoom: 8,
    zoomControl: false
  });

  // Create the autocomplete object, restricting the search predictions to
  // geographical location types.
  const autocomplete = new google.maps.places.Autocomplete(
    document.getElementById("autocomplete"),
    { types: ["geocode"],
      componentRestrictions: {'country': ['gb']},
      fields: ['place_id', 'geometry', 'formatted_address'] }
  );
  // When the user selects an address from the drop-down
  // zoom to the select location and add a marker.
  autocomplete.addListener("place_changed", addCustomerLocation);
}

In this example, once the user has selected the address the addCustomerLocation function is executed. This takes the geometry of the matched result, the customer location, moves the map to that location and adds a marker.

function addCustomerLocation() {
  // Get the place details from the autocomplete object.
  const place = autocomplete.getPlace();

  // Add a marker to the map.
  const marker = new google.maps.Marker({
          map
        });

  marker.setLabel("C");
  marker.setPosition(place.geometry.location);

  // Zoom the map to the marker.
  map.panTo(place.geometry.location);
  map.setZoom(15);
}

You can then see the relationship between the customer and any particular store locations, such as in the image below.

For a visual walkthrough, watch the video tutorials for adding Place Autocomplete to a website or Android app.

For more information, read the Autocomplete for Addresses documentation. See the full source code for populating an address entry form here.

Additionally, the Autocomplete API is also available as a web service and natively in the Places SDK for iOS and Places SDK for Android.

Show the nearest stores: Distance Matrix API

The standard way of organizing a list of stores is by sorting them by distance. Often this distance is calculated simply by using the straight line from a user to the store, but this can be misleading. The straight line might be over an impassable river or through busy roads at a time when another store might be more convenient. This is important when you have multiple locations within a few kilometers of each other.

The Distance Matrix API works by taking a list of origin and destination locations and returning not only the travel distance but also time between them. In a customer's case, the origin would be their location and the destinations would be that of the stores. Origins and destinations can be specified as coordinate pairs or as addresses; the latter will be matched when the service is called. Distance Matrix can be used with a number of extra parameters to show results based on current or future driving times.

Getting started with the Distance Matrix API

Once you have the location of the customer, you can compare this to the location of your stores. Doing this with the Distance Matrix API allows you to avoid the issue of routing people to stores that actually might be farther by car. You can see multiple store locations as shown on the map below:

You can call the Distance Matrix service within the Maps JavaScript API, specifying the customer's origin and the stores' destinations, as given below.

var customer = new google.maps.LatLng(51.494900,-0.146231);
var storeA = new google.maps.LatLng(51.500011,-0.174209);
var storeB = new google.maps.LatLng(51.513072,-0.126105);
var storeC = new google.maps.LatLng(51.481879,-0.137416);

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [customer],
    destinations: [storeA, storeB, storeC]
  }, callback);

The actual response from the service will be a list of matched addresses, distances and durations, similar to that shown below.

{
         "destination_addresses" : [
            "47 Exhibition Rd, Knightsbridge, London SW7 2QA, UK",
            "16 Mercer St, West End, London WC2H 9QE, UK",
            "2 Nine Elms Ln, Nine Elms, London SW11 8AW, UK"
         ],
         "origin_addresses" : [ "70 Buckingham Palace Rd, Belgravia, London SW1W 9TQ, UK" ],
         "rows" : [
            {
               "elements" : [
                  {
                     "distance" : {
                        "text" : "1.8 mi",
                        "value" : 2959
                     },
                     "duration" : {
                        "text" : "9 mins",
                        "value" : 514
                     },
                     "duration_in_traffic" : {
                        "text" : "11 mins",
                        "value" : 650
                     },
                     "status" : "OK"
                  },
                  {
                     "distance" : {
                        "text" : "2.0 mi",
                        "value" : 3246
                     },
                     "duration" : {
                        "text" : "12 mins",
                        "value" : 748
                     },
                     "duration_in_traffic" : {
                        "text" : "16 mins",
                        "value" : 965
                     },
                     "status" : "OK"
                  },
                  {
                     "distance" : {
                        "text" : "2.5 mi",
                        "value" : 4060
                     },
                     "duration" : {
                        "text" : "12 mins",
                        "value" : 696
                     },
                     "duration_in_traffic" : {
                        "text" : "25 mins",
                        "value" : 1491
                     },
                     "status" : "OK"
                  }
               ]
            }
         ],
         "status" : "OK"
      }

You can see the differences in this table, between the straight line distance and the driving distance.

Location Straight Distance Road in Traffic / Time
Store A 1.25 miles 1.7 miles / 11 minutes
Store B 1.52 miles 2.0 miles / 16 minutes
Store C 0.98 miles 2.5 miles / 25 minutes

Even though Store C is the closest by distance, it is the farthest by travel time, since the customer would need to navigate around the river. The distances become even more pronounced if we look at the travel time inclusive of traffic--an important factor when deciding which store to visit. In this case, Store C takes over twice the time to get to than Store A.

Once you have made this request, you can process the match to order the responses by duration of driving time. You can find examples of such a function in the Store Locator codelabs.

On the web, the Distance Matrix service can be used with the Maps JavaScript API.

On Android and iOS, you can use the Distance Matrix web service to provide the same functionality, either directly from the application or remotely through a server proxy. For more information, read the Distance Matrix API documentation.

Add navigation directions: Directions API

Showing customers the directions from within your site or applications means that they don’t need to navigate away from your site; customers won’t be distracted with other pages or see competitors on the map. You could even show the carbon emissions of the specific mode and show the impact of any particular journey.

Getting started with the Directions API

Adding directions to your stores can be done using the Directions service within the Maps JavaScript API. This allows you to not only make requests of the Directions API, but also has functions that allow you to process the results and display them easily on a map.

The following examples can be used to calculate a route between a customer (start) and a store (end) using the DirectionsService and DirectionsRenderer to visualize the response on the map.

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var london = new google.maps.LatLng(51.494900, -0.146231);
  var mapOptions = {
    zoom: 14,
    center: london
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
}

function calcRoute() {
  var start = { lat: 51.494900, lng: -0.146231 };
  var end = { lat: 51.500011, lng: -0.174209 };
  var request = {
    origin: start,
    destination: end,
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function(result, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(result);
    }
  });
}

This can give you an easy way of showing the turn-by-turn details within your application, with the minimum amount of coding.

You can see a working sample of this within the Maps documentation.

On Android and iOS, you can use the Directions web service to provide the same functionality, either directly from the application or remotely through a server proxy. For more information, read the Directions API documentation.

To learn more about these Maps features, read the Maps JavaScript API Documentation or take a look at our step-by-step codelabs to build a store locator.

Tips to further enhance your Store Locator Plus

Google Maps Platform has some extra features that can be added to your Store Locator to further enhance the user’s experience:

  1. Show the outside of your store using Street View. For many locations in the world, Street View can be used to display the outside of the store, offering customers a visual of the location before they arrive. Street View can be provided in either an interactive or static form, depending on whether you want your customers to ‘look around’ the area.
  2. Use static maps when you just want to show the store location. On pages that might just show the details of a specific store, you don’t need the dynamic functionality present in the web libraries. For these pages, you can display a simple image version of the map using the Maps Static API. This provides a quicker loading map that can’t be interacted with, but can provide instant clarity to a particular location, including loading the same styling you use on your dynamic maps. To learn more, watch this video tutorial.
  3. Add extra context using Place Details. You can share the store and travel details shoppers need to know before they visit one of your locations. With rich Place Details like contact information, hours of operation, user ratings, user photos, and temporary closure status, your shoppers will know exactly what to expect when visiting your store. To learn more, watch this video tutorial.

Checkout

Online shopping and ordering have become a ubiquitous part of our lives. From same-day delivery services to booking a taxi or ordering dinner, customers have come to expect a frictionless checkout process. In all of these applications, however, address entry for billing or shipping remains one area that can be both time consuming and cumbersome. A frictionless checkout experience becomes even more important in the mobile world, where complex text entry on a small screen can be frustrating and another barrier for customer conversion.

Checkout consists of the following components:

Place Autocomplete
Autofill an address form. Add type-as-you-go functionality to improve the user experience on all platforms and improve address accuracy with minimum keystrokes.
Geocoding API
Find the latitude/longitude coordinates for a given address (geocoding), or convert the latitude/longitude coordinates of a geographic location to an address (reverse geocoding).
Static Map
Display a fixed image of a map, and optionally add markers, polygons, rectangles, polylines, circles and customized styling. This is useful, for example, if you don't need an interactive map and want to optimize performance and size.

Increase conversion: Place Autocomplete

Place Autocomplete can simplify address entry in your application, leading to higher conversion rates and a seamless experience for your customers. Autocomplete provides a single, quick entry field with ‘type-ahead’ address prediction that can be used to automatically populate a billing or shipping address form.

By incorporating the Place Autocomplete in your online shopping cart, you can:

  • Reduce address entry errors
  • Decrease the number of steps in the checkout process
  • Simplify the address entry experience on mobile or wearable devices
  • Significantly reduce keystrokes and total time required for a customer to place an order

When the user selects the Autocomplete entry box and begins typing, a list of address predictions appear:

When the user selects an address from the list of predictions, you can use the response to verify the address and get the location. Your application can then populate the correct fields of the address entry form:

Getting Started with Place Autocomplete

It only takes a couple of lines of JavaScript code to incorporate Place Autcomplete into your site.

The easiest way is to include the Maps JavaScript API (even if you are not displaying a map) in your site and specify the Places library as shown below, which also executes the initialization function.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initAutocomplete&libraries=places&v=weekly" defer></script>

Next, add a text box to your page, for user input.

<input id="autocomplete" placeholder="Enter your address" type="text"></input>

Finally you need to initialize the Autocomplete service and link it to the named text box:

function initAutocomplete() {
  // Create the autocomplete object, restricting the search predictions to
  // geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
    document.getElementById("autocomplete"),
    { types: ["geocode"],
      componentRestrictions: {'country': ['gb']},
      fields: ['place_id', 'geometry', 'formatted_address'] }
  );
  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
  autocomplete.addListener("place_changed", fillInAddress);
}

In this example once the user has selected the address the fillInAddress function is executed. This takes the selected response and extracts the address components to visualise within a form:

function fillInAddress() {
  // Get the place details from the autocomplete object.
  const place = autocomplete.getPlace();

  for (const component in componentForm) {
    document.getElementById(component).value = "";
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  for (const component of place.address_components) {
    const addressType = component.types[0];

    if (componentForm[addressType]) {
      const val = component[componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

Once you have this data you can use it as the matched address for your user. From a few lines of code, you can make sure the customer enters the right address in a short amount of time.

See the full source code for populating an address entry form in this code sample. For a visual walkthrough, watch the video tutorials for adding Place Autocomplete to a website or Android app.

Additionally, Place Autocomplete is also available as a web service and natively in the Places SDK for iOS and Places SDK for Android.

Considerations when implementing Place Autocomplete

Place Autocomplete has a number of options that allow it to be flexible with its implementation if you want to use more than just the widget. You can use a combination of services to get exactly what you need to match a location in the correct way.

  • Set the types parameter to geocode or address to make sure you only return address or precise addresses to get the most accurate address results and not business matches.
  • Leave fields editable in case certain fields are missed from the match and allow customers to update the address if required.
  • Using the autocomplete predictions allows you to control where you can get the address data from. The AutocompleteService can be used to retrieve an array of predictions objects. These each contain details about the predicted match including distance from origin, description and Place ID. If all you need is the address, the place ID can be used with the Geocoding API, which may be more cost effective under some circumstances.
  • Set the appropriate restrictions and biases if you don’t need to search worldwide. There are a number of parameters that can be used to bias or restrict any match to only specific regions.
    • Use bounds to set the rectangular bounds to constrain for an area, use strictBounds to make sure only addresses in those areas are returned.
    • Use componentRestrictions to restrict responses to a certain set of countries.

Provide visual confirmation: Maps Static API

After address entry, it’s easy to show a map to provide the user visual confirmation of the delivery or pickup location. This will offer the customer additional assurance that the delivery/pickup address is correct, and reduce address failures. The static map can be shown on the page where they enter the address or even sent within the confirmation email when they have completed the transaction.

Both of these use cases can be accomplished with the Maps Static API, which adds an image version of the map to any image tag within a page or email.

Getting started with the Maps Static API

You can use the Maps Static API using a web service call, which will create an image version of a map given the parameters you specify. Like the dynamic map, you can specify the type of map, use the same cloud-based styles and add markers to distinguish the location.

The following call shows a roadmap, with a size of 600x300px, centered on the Brooklyn Bridge at zoom level 13. It also specifies a blue delivery location marker and an online map style.

https://maps.googleapis.com/maps/api/staticmap?center=51.494900,-0.146231&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C51.494900,-0.146231&map_id=8f348d1b5a61d4bb&key=YOUR_API_KEY

This breaks down into the following sections:

API URL
https://maps.googleapis.com/maps/api/staticmap?
map center
center=51.494900,-0.146231
zoom level
zoom=13
image size
size=600x300
type of map
maptype=roadmap
store location markers
markers=color:blue%7Clabel:C%7C51.494900,-0.146231
cloud map style
map_id=8f348d1b5a61d4bb
API Key
key=YOUR_API_KEY

This becomes the image as shown below:

You can find more details about all the options of the Maps Static API here.

Tips to further enhance Checkout

You can further enhance your customer experience by taking advantage of some of the advanced features that the Place Autocomplete has to offer. Here are three tips for improving your Autocomplete address entry box:

  • Allow users to enter an address based on a business or point-of-interest name. The ‘type ahead’ prediction service not only works for addresses, but you may also choose to allow business or landmark names to be entered. After a user enters a business name, it’s easy to retrieve the address with a call to Place Details.
  • Customize the look and feel of the Place Autocomplete box to match your website style. You can also style the autocomplete widget to match the look and feel of your shopping cart. A set of CSS classes are available for you to customize. For more information on how to style your autocomplete box, read the documentation.
  • Bias the address suggestions to a particular geographic region. You can bias the suggestions returned by autocomplete to a particular geographic region, or a viewport defined by a Google Map on your site. You can also restrict the results to a particular country. This ensures your customers are always receiving the most relevant address suggestions. To learn more, read the Place Autocomplete documentation.
Enable Google Maps Platform

To enable APIs or set up billing, we'll guide you through a few tasks:

  1. Pick product(s) below
  2. Select a project
  3. Set up your billing

Build customized map experiences that bring the real world to your users.

Give your users the best way to get from A to Z.

Help users discover the world with rich details.

Continue