Product Locator - implementation guide

Overview

web iOS API

Google Maps Platform is available for web (JS, TS), Android, and iOS, and also offers web services APIs for getting information about places, directions, and distances. The samples in this guide are written for one platform, but documentation links are provided for implementation on other platforms.

When your users see your products online, they want to find the best and most convenient way to get their order. The Product Locator implementation guide and customization tips we provide in this topic are what we recommend as the optimal combination of Google Maps Platform APIs to build great product locator user experiences.

Following this implementation guide, you can help customers see the detailed information they need to find your products, and give them directions to the store that has their item, whether they're driving, cycling, walking, or taking public transit.

Architectural diagram
Architectural diagram (click to enlarge)

Enabling APIs

To implement Product Locator, you must enable the following APIs in the Google Cloud console. The following hyperlinks send you to the Google Cloud console to enable each API for your selected project:

For more information about setup, see Getting started with Google Maps Platform.

Implementation guide sections

Following are the implementations and customizations we'll cover in this topic.

  • The check mark icon is a core implementation step.
  • The star icon is an optional but recommended customization to enhance the solution.
Associating store locations with Google Maps Platform places Match a store location with a place in Google Maps Platform.
Identifying the user's location Add type-as-you-go functionality to improve the user experience on all platforms and improve address accuracy with minimum keystrokes.
Identifying the closest stores Calculate the travel distance and travel time for multiple origins and destinations, optionally specifying various forms of transport such as walking, driving, public transit, or cycling.
Displaying store information Show data-rich information on your stores, so users can navigate to them more easily.
Providing navigation directions Get directions data from origin to destination using various forms of transport such as walking, driving, cycling, and public transit.
Sending directions to mobile In addition to showing directions on your webpage, you can also send directions to a user's phone for navigation using Google Maps on the go.
Showing your locations on an interactive map Create custom map markers to help your locations stand out, and style the map to match your brand colors. Display (or hide) specific points of interest (POI) on your map to help users better orient themselves, and control POI density to prevent map clutter.
Combining custom location data with Place Details Combine your own custom location details with Place Details to give users a rich set of data for making decisions.

Associating store locations with Google Maps Platform places

Getting place IDs

This example uses: Places API Also available: JavaScript

You may have a database of your stores with basic information like the name of that location, its address, and its phone number, and you want to associate it with a place in Google Maps Platform as a set of final destinations your users can pick up products. To fetch the information that Google Maps Platform has about that place, including geographic coordinates and user-contributed information, find the place ID that corresponds to each of the stores in your database. You can make a call to the Find Place endpoint in Places API Place Search and request only the place_id field.

The following shows an example of requesting the place ID for the Google London office:

    https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=google%20london&inputtype=textquery&fields=place_id&key=YOUR_API_KEY&solution_channel=GMP_guides_productlocator_v1_a

You can store this place ID in your database with the rest of your store data and use it as an efficient way to request information about the store. Following are instructions for using the place ID to geocode, retrieve Place Details, and request directions to the place.

Geocoding your locations

This example uses: Geocoding API Also available: JavaScript

If your database of stores has street addresses but not geographic coordinates, use the Geocoding API to obtain the latitude and longitude of that address for the purposes of calculating which stores are nearest to your customer. You can geocode the store on the server side, store the latitudes and longitudes in your database, and refresh at least every 30 days.

Here is an example of using the Geocoding API to obtain the latitude and longitude of the place ID that was returned for the Google London office:

    https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJVSZzVR8FdkgRTyQkxxLQmVU&key=YOUR_API_KEY&solution_channel=GMP_guides_productlocator_v1_a

Identifying the user's location

This example uses: Places Autocomplete Library in the Maps JavaScript API Also available: Android | iOS

A key component in Product Locator is identifying your user's starting location. You can offer two options for the user to specify their starting location: typing in the origin of their search, or granting permissions to web browser geolocation or mobile location services.

Handling typed entries using autocomplete

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 Google Maps Platform Places libraries on mobile devices and the web. When a user types an address, autocomplete fills in the rest through the use of widgets. You can also provide your own autocomplete functionality using the Places libraries directly.

Address autocomplete functionality
Address autocomplete functionality (click to enlarge)

In the following example, add the Place Autocomplete library to your site by adding the libraries=places parameter to the Maps JavaScript API script URL.

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

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

<input id="autocomplete" placeholder="Enter
  starting address, city, or zip code" type="text"></input>

Finally, you need to initialize the Autocomplete service and link it to the named text box. Constraining the Place Autocomplete predictions to geocode types configures your input field to accept street addresses, neighborhoods, cities, and zip codes so users can input any level of specificity to describe their origin. Be sure to request the geometry field so that the response contains latitude and longitude of the user's origin. You'll use these map coordinates to indicate the relationship of your locations to the origin.

// 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", searchFromOrigin);
}

In this example, once the user selects the address, the searchFromOrigin() function starts. This takes the geometry of the matched result that is the user location, then searches for nearest locations based on those coordinates as the origin, discussed in the Identifying the closest stores section.

Showing location options
Showing location options (click to enlarge)

Expand this to see video walkthroughs of adding Place Autocomplete to your app:

Website

Android apps

iOS apps

Using browser geolocation

To request and handle HTML5 browser geolocation, see how to enable a Use my location window:

Browser permission for user location
Web browser permission request (click to enlarge)

Identifying the closest stores

This example uses: Distance Matrix Service, Maps JavaScript API Also available: Distance Matrix API

Once you have the location of the user, you can compare this to where your store locations are. Doing this with the Distance Matrix Service, Maps JavaScript API helps your users select the location that is most convenient for them by driving time or road distance.

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

The Distance Matrix Service, Maps JavaScript API works by taking a list of origin and destination locations and returning not only the travel distance but also the time between them. In a user's case, the origin would be where they currently are, or their desired starting point, and the destinations would be that of the locations. Origins and destinations can be specified as coordinate pairs or as addresses; when you call the service, the service matches the addresses. You can use the Distance Matrix Service, Maps JavaScript API with additional parameters to show results based on current or future driving times.

The following example calls the Distance Matrix Service, Maps JavaScript API, specifying the user's origin and 25 store locations at a time.

function getDistances(place) {
  let distanceMatrixService = new google.maps.DistanceMatrixService();
  const origins = [place];
  return new Promise((resolve, reject) => {
    const callback = (response, status) => {
      if (status === google.maps.DistanceMatrixStatus.OK && response) {
        resolve(response);
      } else {
        reject(status);
      }
    };
    distanceMatrixService.getDistanceMatrix(
      {
        origins,
        destinations: stores.slice(0, 25).map((store) => store.location),
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
      },
      callback
    );
  });
}

function update(location) {
  if (!location) {
    return;
  }

  // ...

  // sort by spherical distance
  stores.sort((a, b) => {
    return (
      google.maps.geometry.spherical.computeDistanceBetween(
        new google.maps.LatLng(a.location),
        location
      ) -
      google.maps.geometry.spherical.computeDistanceBetween(
        new google.maps.LatLng(b.location),
        location
      )
    );
  });

  // display travel distance and time
  getDistances(location)
    .then((response) => {
      for (let i = 0; i < response.rows[0].elements.length; i++) {
        stores[i].address = response.destinationAddresses[i];
        stores[i].travelDistance = response.rows[0].elements[i].distance.value;
        stores[i].travelDistanceText =
          response.rows[0].elements[i].distance.text;
        stores[i].travelDuration = response.rows[0].elements[i].duration.value;
        stores[i].travelDurationText =
          response.rows[0].elements[i].duration.text;
      }
    })
    .finally(() => {
      renderCards(stores);
      autocompleteInput.disabled = false;
      isUpdateInProgress = false;
    });
}

For each nearby location you can display stock status of the product based on your inventory database.

Displaying store information

This example uses: Places Library, Maps JavaScript API Also available: Places SDK for Android | Places SDK for iOS | Places API

You can share rich Place Details like contact information, hours of operation, and current open status to help customers pick their preferred location or finalize their order.

After making a call to the Maps JavaScript API to get Place Details, you can filter and render the response.

Showing store options
Showing store options (click to enlarge)

To request Place Details, you will need the place ID of each of your locations. See Getting place IDs to retrieve the place ID of your location.

The following Place Details request returns the address, coordinates, website, phone number, rating, and hours for the Google London place ID:

var request = {
  placeId: 'ChIJVSZzVR8FdkgRTyQkxxLQmVU',
  fields: ['name', 'formatted_phone_number', 'geometry', 'opening_hours', 'rating', 'utc_offset_minutes', 'website']
};

service = new google.maps.places.PlacesService(map); service.getDetails(request, callback);

function callback(place, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { createMarker(place); } }


Enhancing Product Locator

Depending on your business or users' needs, you can further enhance the user’s experience.

Providing navigation directions

This example uses: Maps JavaScript API Directions Service Also available: Directions API web service for use on Android and iOS, either directly from the application or remotely through a server proxy

When you show users directions from within your site or applications, your users don’t need to navigate away from your site and get distracted with other pages or see competitors on the map. You could even show the carbon emissions of the specific travel mode and show the impact of any particular journey using a carbon data set you may own.

The Directions Service also has functions that let you process the results and display them easily on a map.

Following is an example of displaying a directions panel. For more information on the sample, see Displaying text directions.

Sending directions to mobile

To make it even easier for users to reach a location, you can text or email them a directions link. When they click it, the Google Maps app will launch on their phone if it is installed, or maps.google.com will load in their device's web browser. Both of these experiences provide the user with the option to use turn-by-turn navigation, including voice guidance, to reach the destination.

Use Maps URLs to compose a directions URL like the following, with the URL-encoded place name as the destination parameter and place ID as the destination_place_id parameter. There is no cost to compose or use Maps URLs, so you don't need to include an API key in the URL.

https://www.google.com/maps/dir/?api=1&destination=Google%20London&destination_place_id=ChIJVSZzVR8FdkgRTyQkxxLQmVU

You can optionally provide an origin query parameter using the same address format as the destination. But by omitting it, the directions start from the user's current location, which may be different from where they were using your Product Locator app. Maps URLs provide additional query parameter options, such as travelmode and dir_action=navigate to launch the directions with navigation turned on.

This clickable link, which extends the example URL above, sets the origin as a London football stadium and uses travelmode=transit to provide public transit directions to the destination.

To send a text or email containing this URL, we currently recommend using a third-party application such as twilio. If you're using App Engine, you can use third-party companies to send SMS messages or email. For more information, see Sending Messages with Third-Party Services.

Showing your locations on an interactive map

Using dynamic maps

This example uses: Maps JavaScript API Also available: Android | iOS

A locator is an important part of the user experience. Some sites, however, may lack even a simple map, requiring users to leave the site or the app to find a nearby location. This means a suboptimal experience for users 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.

Adding a dynamic map to your page—that is, a map that users can move around, zoom in and out on, and get details about different locations and points of interest—can be done with a few lines of code.

First, you need to include the Maps JavaScript API in the page. This is done through linking the following script in your HTML page.

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

The URL references the JavaScript initMap function that runs when the page loads. In the URL, you can also 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. Setting a region also ensures that the behavior of apps used outside of the United States is biased towards the region you set. View the Google Maps Platform Coverage Details for a full list of supported languages and regions, and learn more about region parameter usage.

Next, you need an HTML div to place your map on the page. This is the place where the map will be displayed.

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

The next step is to set the basic functionality of your map. This is done in the initMap script function specified in the script URL. In this script, shown in the following example, you can set the initial location, the type of map, and which controls will be available on the map for your users. Notice that getElementById() references the "map" div ID above.

function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: { lat: 51.485925, lng: -0.129500 },
zoomControl: false
});
}

For a 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 tuning of controls, are optional as you determine the level of interaction with the map.

Customizing your map

You can change your map's appearance and details in a number of ways. For example, you can:

  • Create your own custom markers to replace the default map pins.
  • Change the colors of map features to reflect your brand.
  • Control which points of interest you display (attractions, food, lodging, and so on) and at what density, letting you focus user attention on your locations while highlighting the landmarks that help users get to the nearest location.

Creating custom map markers

You can customize your markers by changing the default color (possibly showing whether a location 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 users, such as opening hours, phone number, or even photos. You can also create custom markers that are raster, vector, draggable, and even animated.

Following is a sample map that uses custom markers. (See the source code in the Maps JavaScript API custom markers topic.)

For detailed information, see the markers documentation for JavaScript (web), Android, and iOS.

Styling your map

Google Maps Platform lets you style your map in ways that help users find the closest location, get there as quickly as possible, and help you reinforce your brand. For example, you can change map colors to match your branding, and you can reduce distractions on the map by controlling the points of interest that are visible to users. Google Maps Platform also provides a number of map starter templates, some of which are optimized for different industries, such as travel, logistics, real estate, and retail.

You can create or modify map styles in the Google Cloud console Map Styles page in your project.

Expand to see animations of map style creation and styling in the Cloud console:

Industry map styles

This animation shows predefined industry-specific map styles you can use. These styles provide an optimal starting point for each type of industry. For example, the Retail map style reduces points of interest on the map, letting users focus on your locations, as well as the landmarks to help them get to the closest location as quickly and confidently as possible.

On the Map Style page, the mouse clicks Create New Map Style. On the
                New Map Style page, the mouse clicks the radio button next to each of the
                following industry optimized styles: Travel, Logistics, Real Estate, and
                Retail. As each button is clicked, the map style description and graphical
                preview changes.

Points of interest control

This animation sets the marker color for points of interest and increases the POI density on the map style. The higher the density, the more POI markers appear on the map.

On the Map Style page, the mouse clicks Create New Map Style. On the
              New Map Style page, under Create Your Own Style, the Google Map radio button
              is selected. The mouse clicks the Atlas radio button for the Atlas style,
              then clicks Open in Style Editor. In the Style Editor, the mouse clicks
              the Points of Interest feature, then clicks the Icon element, setting the
              color to red. The mouse then selects the POI Density checkbox and slides
              the density control to the right for maximum density. More and more red
              markers appear on the map preview as density increases. The mouse then moves
              to the Save button.

Each map style has its own ID. After you publish a style in the Cloud console, you reference that map ID in your code—which means you can update a map style in real time without refactoring your app. The new look will automatically appear in the existing application and be used across platforms. The following examples show how to add a map ID to a web page using the Maps JavaScript API.

By including one or more map_ids in the script URL, the Maps JavaScript API automatically makes those styles available for faster map rendering when you call those styles in your code.

<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&map_ids=MAP_IDs&callback=initMap&solution_channel=GMP_guides_productlocator_v1_a">
</script>

The following code displays a styled map on the web page. (Not shown is an HTML <div id="map"></div> element where the map will appear on the page.)

map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 51.485925, lng: -0.129500},
zoom: 12,
mapId: '1234abcd5678efgh'
});

Learn more about incorporating cloud-based maps styling in JavaScript (web), Android, and iOS.

Combining custom location data with Place Details

In the previous Showing your locations on an interactive map section, we covered using Place Details to give users a rich level of information about your locations, such as opening hours, photos, and reviews.

It's helpful to understand the cost of different data fields in Place Details, which are categorized as Basic, Contact, and Atmosphere Data. To manage your costs, one strategy is to combine the information you already have about your locations with the fresh information (usually Basic and Contact Data) from Google Maps such as temporary closure, holiday hours, and user ratings, photos, and reviews. If you already have the contact information for your stores, you won't need to request those fields from Place Details and can constrain your request to fetch only Basic or Atmosphere Data fields depending on what you want to display.

You may have your own place data to supplement or use instead of Place Details. The codelab for the full-stack locator provides an example of using GeoJSON with a database to store and retrieve your own location details.