On-demand Rides and Deliveries Solution is currently available only to select partners.

Getting started with the Consumer SDK for JavaScript

Stay organized with collections Save and categorize content based on your preferences.

The JavaScript SDK lets you visualize the location of vehicles and locations of interest tracked in Fleet Engine. The library contains a JavaScript map component that is a drop-in replacement for a standard google.maps.Map entity and data components to connect with Fleet Engine. Using the JavaScript SDK, you can provide a customizable, animated trip and order progress experience from your web application.

Components

The JavaScript SDK provides components for visualization of vehicles and waypoints, as well as raw data feeds for a driver's ETA or the remaining distance to drive.

Trip and Order Progress map view

The map view component visualizes the location of vehicles and waypoints. If the route for a vehicle is known, the map view component animates that vehicle as it moves along its predicted path.

Trip location provider

The JavaScript SDK includes a trip location provider that feeds location information for tracked objects into the trip and order progress map.

You can use the trip location provider to track:

  • The pickup or dropoff location of a trip.
  • The location and route of the vehicle assigned to the trip.

Tracked location objects

The location provider tracks the location of objects such as waypoints and vehicles.

Origin location

The origin location is the location where a journey starts. It marks the pickup location.

Destination location

The destination location is the location where a journey ends. It marks the dropoff location.

Waypoint location

A waypoint location is any location along the route of a tracked journey. For example, each stop on a bus route is a waypoint location.

Vehicle location

The vehicle location is the tracked location of a vehicle. It may optionally include a route for the vehicle.

Authentication token fetcher

To control access to the location data stored in Fleet Engine, you must implement a JSON Web Token (JWT) minting service for Fleet Engine on your server. Then implement an authentication token fetcher as part of your web application, using the JavaScript SDK to authenticate access to the location data.

Styling options

Marker and polyline styles determine the look and feel of the tracked location objects on the map. You can use custom styling options to change the default styling to match the styling of your web application.

Controlling the visibility of tracked locations

This section describes the visibility rules for tracked location objects on the map for Fleet Engine predefined location providers. Custom or derived location providers may change the visibility rules.

Vehicles

A ridesharing vehicle is visible from the time it is assigned to a trip to the time of dropoff. If the trip is canceled, the vehicle is longer visible.

All other location markers

All other location markers for origin, destination, and waypoints are always shown on the map. For example, a ridesharing dropoff location or a shipment delivery location is always shown on the map, regardless of the state of the trip or delivery.

Get started with the JavaScript SDK

Before using the JavaScript SDK, make sure you are familiar with Fleet Engine and with getting an API key.

To track a ridesharing trip, first create a trip ID claim.

Create a trip ID claim

To track a trip using the trip location provider, create a JSON Web Token (JWT) with a trip ID claim.

To create the JWT payload, add an additional claim in the authorization section with the key tripid and set its value to the trip ID.

The following example shows how to create a token for tracking by trip ID:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "private_key_id_of_consumer_service_account"
}
.
{
  "iss": "consumer@yourgcpproject.iam.gserviceaccount.com",
  "sub": "consumer@yourgcpproject.iam.gserviceaccount.com",
  "aud": "https://fleetengine.googleapis.com/",
  "iat": 1511900000,
  "exp": 1511903600,
  "scope": "https://www.googleapis.com/auth/xapi",
  "authorization": {
     "tripid": "tid_12345",
   }
}

Create an authentication token fetcher

You can create an authentication token fetcher to retrieve a token minted with the appropriate claims on your servers using a service account certificate for your project. It is important to only mint tokens on your servers and never share your certificates on any clients. Otherwise, you will compromise the security of your system.

The following example shows how to create an authentication token fetcher:

JavaScript

function authTokenFetcher(options) {
  // options is a record containing two keys called 
  // serviceType and context. The developer should
  // generate the correct SERVER_TOKEN_URL and request
  // based on the values of these fields.
  const response = await fetch(SERVER_TOKEN_URL);
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  const data = await response.json();
  return {
    token: data.Token,
    expiresInSeconds: data.ExpiresInSeconds
  };
}

TypeScript

function authTokenFetcher(options: {
  serviceType: google.maps.journeySharing.FleetEngineServiceType,
  context: google.maps.journeySharing.AuthTokenContext,
}): Promise<google.maps.journeySharing.AuthToken> {
  // The developer should generate the correct
  // SERVER_TOKEN_URL based on options.
  const response = await fetch(SERVER_TOKEN_URL);
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  const data = await response.json();
  return {
    token: data.Token,
    expiresInSeconds: data.ExpiresInSeconds
  };
}

When implementing the server-side endpoint for minting the tokens, keep the following in mind:

  • The endpoint must return an expiry time for the token; in the example above, it is given as data.ExpiresInSeconds.
  • The authentication token fetcher must pass the expiry time (in seconds, from time of issuance) to the library, as shown in the example.

Loading a map from HTML

The following example shows how to load the JavaScript SDK from a specified URL. The callback parameter executes the initMap function after the API loads. The defer attribute lets the browser continue rendering the rest of your page while the API loads. Note that the v=beta parameter must be specified.

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

Following a trip

This section shows how to use the JavaScript SDK to follow a ridesharing or delivery trip. Make sure to load the library from the callback function specified in the script tag before running your code.

Instantiate a trip location provider

The JavaScript SDK predefines a location provider for the Fleet Engine Ridesharing API. Use your project ID and a reference to your token factory to instantiate it.

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

Initialize the map view

After loading the JavaScript SDK, initialize the map view and add it to the HTML page. Your page should contain a <div> element that holds the map view. The <div> element is named map_canvas in the example below.

To avoid race conditions, set the trip ID for the location provider in the callback that is invoked after the map is initialized.

JavaScript

const mapView = new 
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'), 
  locationProvider: locationProvider,
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.tripId = 'your-trip-id';

// Give the map an initial viewport to allow it to 
// initialize; otherwise, the 'ready' event above may 
// not fire. The user also has access to the mapView
// object to customize as they wish.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
locationProvider.tripId = 'your-trip-id';

// Give the map an initial viewport to allow it to 
// initialize; otherwise, the 'ready' event above may 
// not fire. The user also has access to the mapView 
// object to customize as they wish.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

Listen to change events

You can retrieve meta information about a trip from the task object using the location provider. The meta information includes the ETA and remaining distance before pickup or dropoff. Changes to the meta information trigger an update event. The following example shows how to listen to these change events.

JavaScript

locationProvider.addListener('update', e => {
  // e.trip contains data that may be useful
  // to the rest of the UI.  
  console.log(e.trip.dropOffTime);
});

TypeScript

locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
  // e.trip contains data that may be useful
  // to the rest of the UI.  
  console.log(e.trip.dropOffTime);
});

Handle errors

Errors that arise asynchronously from requesting trip information trigger error events. The following example shows how to listen for these events in order to handle errors.

JavaScript

locationProvider.addListener('error', e => {
  // e.error contains the error that triggered the 
  // event
  console.error(e.error);
});

TypeScript

locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error contains the error that triggered the 
  // event
  console.error(e.error);
});

Note: Make sure to wrap library calls in try...catch blocks to handle unanticipated errors.

Customizing the look and feel of maps and tracked location objects

To customize the look and feel of the maps component, style your map using cloud-based tooling or JSON style declaratations. You can also customize the look and feel of tracked location objects such as routes, vehicles, and stops.

Using cloud-based map styling

Cloud-based maps styling lets you create and edit map styles for any of your apps that use Google Maps from the Google Cloud console, without requiring any changes to your code. The map styles are saved as map IDs in your Cloud project. To apply a style to your JavaScript SDK map, specify a mapId and any other mapOptions when you create the JourneySharingMapView. The mapId field cannot be changed or added after the JourneySharingMapView has been instantiated. The following example shows how to enable a previously created map style with a map ID.

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // and any other styling options.
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // and any other styling options.
});

Change the styling and visibility of routes

To configure the styling and visibility of taken and anticipated routes, use custom styling options. For more information, see PolylineOptions interface.

The following example shows how to configure the styling and visibility of anticipated routes. To configure the styling and visibility of taken routes, use takenRoutePolylineSetup instead of anticipatedRoutePolylineSetup.

JavaScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function anticipatedRoutePolylineSetup({
    defaultPolylineOptions, defaultVisible}) {
  // If this function is not specified, the 
  // PolylineOptions object contained in 
  // defaultPolylineOptions is used to render the
  // anticipated route polyline. visible property sets the
  // polyline's visibility. Modify this object and 
  // pass it back to customize the style of the map.
  defaultPolylineOptions.strokeOpacity = 0.5;
  defaultPolylineOptions.strokeColor = 'red';
  return {
    polylineOptions: defaultPolylineOptions,
    visible: true
  };
}

// As an alternative, set a static PolylineOptions to 
// use for the anticipated route:
const anticipatedRoutePolylineOptionsSetup = {
  polylineOptions: {
    strokeOpacity: 0.5,
    strokeColor: 'red',
    …
  },
  visible: true,
};

TypeScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function anticipatedRoutePolylineSetup(options: {
  defaultPolylineOptions: google.maps.PolylineOptions,
  visible: boolean,
}): {
  polylineOptions: google.maps.PolylineOptions,
  visible: boolean,
} {
  // If this function is not specified, the 
  // PolylineOptions object contained in 
  // defaultPolylineOptions is used to render the
  // anticipated route polyline. visible property sets the
  // polyline's visibility. Modify this object and 
  // pass it back to customize the style of the map.
  options.defaultPolylineOptions.strokeOpacity = 0.5;
  options.defaultPolylineOptions.strokeColor = 'red';
  return {
    polylineOptions: options.defaultPolylineOptions,
    visible: true
  };
}

// As an alternative, set a static PolylineOptions to 
// use for the anticipated route:
const anticipatedRoutePolylineSetup = {
  polylineOptions: {
    strokeOpacity: 0.5,
    strokeColor: 'red',
    …
  },
  visible: true,
};

Change the styling and icons of vehicle markers

Use custom styling providers to configure the styling and icon used to represent a vehicle. The following example shows how to configure a vehicle marker's styling and icon.

JavaScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function vehicleMarkerSetup({defaultMarkerOptions}) {
  // If this function is not specified, the 
  // MarkerOptions object contained in 
  // defaultMarkerOptions is used to render the
  // vehicle marker. Modify this object and pass it
  // back to customize the style of the map.
  defaultMarkerOptions.opacity = 0.5;
  defaultMarkerOptions.icon = MY_ICON;
  return {markerOptions: defaultMarkerOptions};
}

// As an alternative, set a static MarkerOptions to use
// for the vehicle marker:
const vehicleMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    …
}};

TypeScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function vehicleMarkerSetup(options: {
  defaultMarkerOptions: google.maps.MarkerOptions,
}): {markerOptions: google.maps.MarkerOptions} {
  // If this function is not specified, the 
  // MarkerOptions object contained in 
  // defaultMarkerOptions is used to render the
  // vehicle marker. Modify this object and pass it
  // back to customize the style of the map.
  options.defaultMarkerOptions.opacity = 0.5;
  options.defaultMarkerOptions.icon = MY_ICON;
  return {
    markerOptions: options.defaultMarkerOptions,
  };
}

// As an alternative, set a static MarkerOptions to use
// for the vehicle marker:
vehicleMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    …
}};

Change origin, destination, and waypoint icons

You can use custom styling options to configure the icon used to represent an origin, waypoint, or destination location. The styling options are defined and attached to the map view in the same way as changing the icons of vehicle markers.

The following example shows how to configure an origin marker's icon. To configure the icon for a destination or waypoint icon, use destinationMarkerSetup or waypointMarkerSetup instead of originMarkerSetup.

JavaScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function originMarkerSetup({defaultMarkerOptions}) {
  // If this function is not specified, the 
  // MarkerOptions object contained in
  // defaultMarkerOptions will be used to render the
  // origin marker. Modify this object and pass it
  // back to customize the style of the map.
  defaultMarkerOptions.opacity = 0.5;
  defaultMarkerOptions.icon = MY_ICON;
  return {markerOptions: defaultMarkerOptions};
}

// As an alternative, set a static MarkerOptions to use
// for the origin marker:
const originMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    ...
}};

TypeScript

// This function is specified in the
// JourneySharingMapView constructor's options 
// parameter.
function originMarkerSetup(options: {
  defaultMarkerOptions: google.maps.MarkerOptions,
}): {markerOptions: google.maps.MarkerOptions} {
  // If this function is not specified, the 
  // MarkerOptions object contained in 
  // defaultMarkerOptions is used to render the
  // origin marker. Modify this object and pass it
  // back to customize the style of the map.
  options.defaultMarkerOptions.opacity = 0.5;
  options.defaultMarkerOptions.icon = MY_ICON;
  return {
    markerOptions: options.defaultMarkerOptions,
  };
}

// As an alternative, set a static MarkerOptions to use
// for the origin marker:
originMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    ...
}};

Display an InfoWindow for a vehicle or location marker

You can use an InfoWindow to display additional information about a vehicle or location marker.

The following example shows how to create an InfoWindow and attach it to a vehicle marker:

JavaScript

// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
    {disableAutoPan: true});

locationProvider.addListener('update', e => {
  const stopsCount = e.trip.remainingWaypoints.length;
  infoWindow.setContent(
      `Your vehicle is ${stopsCount} stops away.`);

  // 2. Attach the info window to a vehicle marker.   
  // This property can return multiple markers.
  const marker = mapView.vehicleMarkers[0];
  infoWindow.open(mapView.map, marker);
});

// 3. Close the info window.
infoWindow.close();

TypeScript

// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
    {disableAutoPan: true});

locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
  const stopsCount = e.trip.remainingWaypoints.length;
  infoWindow.setContent(
      `Your vehicle is ${stopsCount} stops away.`);

  // 2. Attach the info window to a vehicle marker.   
  // This property can return multiple markers.
  const marker = mapView.vehicleMarkers[0];
  infoWindow.open(mapView.map, marker);
});

// 3. Close the info window.
infoWindow.close();

Disable automatic fitting

You can stop the map from automatically fitting the viewport to the vehicle and anticipated route by disabling automatic fitting. The following example shows how to disable automatic fitting you configure the trip and order progress map view.

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  automaticViewportMode:
      google.maps.journeySharing
          .AutomaticViewportMode.NONE,
  ...
});

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  automaticViewportMode:
      google.maps.journeySharing
          .AutomaticViewportMode.NONE,
  ...
});

Replace an existing map

You can use the JavaScript SDK to replace an existing map that includes markers or other customizations without losing those customizations.

For example, suppose you have a web page with a standard google.maps.Map entity on which a marker is shown:

<!DOCTYPE html>
<html>
  <head>
    <style>
       /* Set the size of the div element that contains the map */
      #map {
        height: 400px;  /* The height is 400 pixels */
        width: 100%;  /* The width is the width of the web page */
       }
    </style>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>
    <script>
// Initialize and add the map
function initMap() {
  // The location of Uluru
  var uluru = {lat: -25.344, lng: 131.036};
  // The map, centered at Uluru
  var map = new google.maps.Map(document.getElementById('map'));
  map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

  // The marker, positioned at Uluru
  var marker = new google.maps.Marker({position: uluru, map: map});
}
    </script>
    <!-- Load the API from the specified URL.
       * The async attribute allows the browser to render the page while the API loads.
       * The key parameter will contain your own API key (which is not needed for this tutorial).
       * The callback parameter executes the initMap() function.
    -->
    <script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

To add the JavaScript SDK:

  1. Add code for the authentication token factory.
  2. Initialize a location provider in the initMap() function.
  3. Initialize the map view in the initMap() function. The view contains the map.
  4. Move your customization into the callback function for the map view initialization.
  5. Add the location library to the API loader.

The following example shows the changes to be made:

<!DOCTYPE html>
<html>
  <head>
    <style>
       /* Set the size of the div element that contains the map */
      #map {
        height: 400px;  /* The height is 400 pixels */
        width: 100%;  /* The width is the width of the web page */
       }
    </style>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>
    <script>
let locationProvider;

// (1) Authentication Token Fetcher
function authTokenFetcher(options) {
  // options is a record containing two keys called 
  // serviceType and context. The developer should
  // generate the correct SERVER_TOKEN_URL and request
  // based on the values of these fields.
  const response = await fetch(SERVER_TOKEN_URL);
      if (!response.ok) {
        throw new Error(response.statusText);
      }
      const data = await response.json();
      return {
        token: data.Token,
        expiresInSeconds: data.ExpiresInSeconds
      };
}

// Initialize and add the map
function initMap() {
  // (2) Initialize location provider.
  locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
    YOUR_PROVIDER_ID,
    authTokenFetcher,
  });

  // (3) Initialize map view (which contains the map).
  const mapView = new google.maps.journeySharing.JourneySharingMapView({
    element: document.getElementById('map'), 
    locationProvider: locationProvider,
    // any styling options
  });

  locationProvider.tripId = TRIP_ID;

    // (4) Add customizations like before.

    // The location of Uluru
    var uluru = {lat: -25.344, lng: 131.036};
    // The map, centered at Uluru
    var map = mapView.map;
    map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
    // The marker, positioned at Uluru
    var marker = new google.maps.Marker({position: uluru, map: map});
  };
}
    </script>
    <!-- Load the API from the specified URL
      * The async attribute allows the browser to render the page while the API loads
      * The key parameter will contain your own API key (which is not needed for this tutorial)
      * The callback parameter executes the initMap() function
      *
      * (5) Add the SDK to the API loader.
    -->
    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=beta&libraries=journeySharing">
    </script>
  </body>
</html>

If you operate a trip with the specified ID near Uluru, it will now be rendered on the map.