Last Mile Fleet Solution is currently available only to select customers. Contact sales to learn more.

Track shipments with the JavaScript Shipment Tracking Library

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

The JavaScript Shipment Tracking Library 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 Shipment Tracking Library, you can provide a customizable, animated shipment tracking experience from your web application.

Components

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

Shipment Tracking map view

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

Shipment location provider

A shipment location provider feeds location information for tracked objects into the shipment tracking map for first and last mile shipment tracking.

You can use the shipment location provider to track:

  • The pickup or delivery location of a shipment.
  • The location and route of the delivery vehicle.

Tracked location objects

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

Origin location

The origin location is the location where a journey starts. Origin location is not used for Google Maps Platform Last Mile Fleet Solution.

Destination location

The destination location is the location where a journey ends. For shipment tracking, it is the pickup location for first mile tracking and the delivery location for last mile tracking.

Vehicle stop

A vehicle stop is any location along the route of a tracked journey. For example, the location where a vehicle stops for one or more delivery tasks is a vehicle stop.

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 Journey Sharing Library 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 vehicle become visible within the Shipment Tracking Library when the associated task has been assigned to the vehicle and the vehicle is within five stops of the task. The vehicle visibility ends when the task is completed or canceled.

A vehicle is not visible during an unavailability task (for example, if the driver is taking a break or the vehicle is being refueled).

All other location markers

All other location markers for origin, destination, and vehicle stops are always shown on the map. For example, a shipment delivery location is always shown on the map, regardless of the state of the delivery.

Get started with the JavaScript Journey Sharing Library

Before using the JavaScript Journey Sharing Library make sure you are familiar with Fleet Engine and with getting an API key.

To track a delivery, first create a tracking ID claim.

Create a tracking ID claim

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

To create the JWT payload, add an additional claim in the authorization section with the key trackingid. Set its value to the shipment tracking ID.

The following example shows how to create a token for tracking by tracking 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": {
     "trackingid": "tid_54321",
   }
}

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 Shipment Tracking Library 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 shipment

This section shows how to use the JavaScript Shipment Tracking Library to follow a shipment pickup or delivery. Make sure to load the library from the callback function specified in the script tag before running your code.

Instantiate a shipment location provider

The JavaScript Shipment Tracking Library predefines a location provider for the Fleet Engine Deliveries API. Use your project ID and a reference to your token factory to instantiate it.

JavaScript

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

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

TypeScript

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

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

Initialize the map view

After loading the JavaScript Journey Sharing library, initialize the map view and add it to the HTML page. Your page should contain a <div> element that holds the map view. In the following example, the <div> element is named map_canvas.

To avoid race conditions, set the tracking 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,
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a tracking ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.trackingId = 'your-tracking-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({
  document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
 // Any undefined styling options will use defaults.
});

// If you did not specify a tracking ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.trackingId = 'your-tracking-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);

Tracking ID

The tracking ID supplied to the location provider may correspond to several tasks; for example, a pickup and a delivery task for the same package, or several failed delivery attempts. One task is selected to be shown on the shipment tracking map. The task to be shown is determined as follows:

  1. If there is exactly one open pickup task, it is shown. An error is generated if there are multiple open pickup tasks.
  2. If there is exactly one open delivery task, it is shown. An error is generated if there are multiple open delivery tasks.
  3. If there are closed delivery tasks:
    • If there is exactly one closed delivery task, it is shown.
    • If there are multiple closed delivery tasks, the one with the most recent outcome time is shown.
    • If there are multiple closed delivery tasks, none of which have an outcome time, an error is generated.
  4. If there are closed pickup tasks:
    • If there is exactly one closed pickup task, it is shown.
    • If there are multiple closed pickup tasks, the one with the most recent outcome time is shown.
    • If there are multiple closed pickup tasks, none of which have an outcome time, an error is generated.
  5. Otherwise, no task is shown.

Listen to change events

You can retrieve meta information about a task from the task object using the location provider. The meta information includes the ETA, number of remaining stops, and remaining distance before pickup or delivery. 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.task contains data that may be useful
  // to the rest of the UI.
  console.log(e.task.taskDuration);
});

TypeScript

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

Handle errors

Errors that arise asynchronously from requesting shipment 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 is the error that triggered the event.
  console.error(e.error);
});

TypeScript

locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error is 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 Shipment Tracking 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'
  }
  // Any other styling options.
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // 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 will be 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 will be 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 vehicle stop icons

You can use custom styling options to configure the icon used to represent an origin, vehicle stop, 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 vehicle stop 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 is 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.task.remainingVehicleJourneySegments.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 journey sharing map view.

JavaScript

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

TypeScript

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

locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineShipmentLocationProviderUpdateEvent) => {
  const stopsCount =
      e.task.remainingVehicleJourneySegments.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();

Replace an existing map

You can use the JavaScript Shipment Tracking Library 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, initially centered at Mountain View, CA.
  var map = new google.maps.Map(document.getElementById('map'));
  map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

  // The marker, now 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 Journey Sharing library:

  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.FleetEngineShipmentLocationProvider({
    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.trackingId = TRACKING_ID;

    // (4) Add customizations like before.

    // The location of Uluru
    var uluru = {lat: -25.344, lng: 131.036};
    // The map, initially centered at Mountain View, CA.
    var map = mapView.map;
    map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
    // The marker, now 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 journey sharing library 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 have a tracked package with the specified ID near Uluru, it will now be rendered on the map.