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

Track your fleet with the JavaScript Fleet Tracking Library

The JavaScript Fleet Tracking Library lets you visualize the locations of vehicles in their fleets in near real time. The library uses the Deliveries API to allow visualization of delivery vehicles as well as tasks. Like the JavaScript Shipment Tracking Library, it 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.

Components

The JavaScript Fleet Tracking Library provides components for visualization of delivery vehicles and stops, as well as raw data feeds for ETA or remaining distance to a delivery.

Fleet Tracking map view

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

Fleet Tracking map view example

Location providers

Location providers work with information stored in Fleet Engine to send location information for tracked objects into the journey sharing map.

Delivery vehicle location provider

The delivery vehicle location provider displays a single delivery vehicle's location information. It has information on the vehicle location as well as the tasks that were completed by the delivery vehicle.

Delivery fleet location provider

The delivery fleet location provider displays multiple vehicles' location information. You can filter for specific vehicles or locations, or you can show the whole fleet.

Controlling the visibility of tracked locations

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

Delivery vehicles

A delivery vehicle is visible as soon as it is created in Fleet Engine, and is visible throughout its route regardless of its tasks.

Task location markers

Planned vehicle stops are shown on the map as vehicle stop markers. Markers for completed tasks are displayed with a different style than a vehicle's planned stops.

The location of task outcomes are displayed with task outcome markers. Tasks with a SUCCEEDED outcome are displayed with successful task markers, while all other tasks are displayed with unsuccessful task markers.

Get started with the JavaScript Fleet Tracking Library

Before using the JavaScript Fleet Tracking Library make sure you are familiar with Fleet Engine and with getting an API key. Then create a task ID and delivery vehicle ID claim.

Create a task ID and delivery vehicle ID claim

To track delivery vehicles using the delivery vehicle location provider, create a JSON Web Token (JWT) with a task ID and delivery vehicle ID claim.

To create the JWT payload, add an additional claim in the authorization section with the keys taskid and deliveryvehicleid and set the value of each key to *. The token should be created using the Fleet Engine Service Super User Cloud IAM role. Note that this grants broad access to create, read, and modify Fleet Engine entities, and should only be shared with trusted users.

The following example shows how to create a token for tracking by vehicle and task:

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

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 Journey Sharing 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 delivery vehicle

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

Instantiate a delivery vehicle location provider

The JavaScript Fleet 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
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher,

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

TypeScript

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

          // Optionally, you may specify
          // deliveryVehicleId to immediately start
          // tracking.
          deliveryVehicleId: 'your-delivery-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. The <div> element is named map_canvas in the example below.

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 delivery vehicle ID in the 
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId 
                        = 'your-delivery-vehicle-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('Times Square, New York, NY');
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 delivery vehicle ID in the 
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId 
                        = 'your-delivery-vehicle-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('Times Square, New York, NY');
mapView.map.setZoom(14);

Listen to change events

You can retrieve meta information about a task from the deliveryVehicle object using the location provider. The meta information includes the ETA and remaining distance before the vehicle's next 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.deliveryVehicle contains data that may be        
  // useful to the rest of the UI.  
  if (e.deliveryVehicle) {
    console.log(e.deliveryVehicle.remainingDuration);
  }
});

TypeScript

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

Listen for errors

Errors that arise asynchronously from requesting delivery vehicle 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.journeySharing.ErrorEvent) => { // e.error is the error that triggered the event. console.error(e.error); });

Viewing a delivery fleet

This section shows how to use the JavaScript Journey Sharing library to view a delivery fleet. Make sure to load the library from the callback function specified in the script tag before running your code.

Instantiating a delivery fleet location provider

The JavaScript Fleet Tracking Library predefines a location provider that fetches multiple vehicles from the FleetEngine Deliveries API. Use your project ID as well as as a reference to your token fetcher to instantiate it.

JavaScript

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

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify required attributes
          // (on the delivery vehicle's 'attributes'
          // field) to limit which delivery vehicles
          // are retrieved.
          deliveryVehicleFilterOptions: {
            requiredAttributes: {
              requiredAttribute1: 'foo',
              requiredAttribute2: 'bar',
            },
          },
        });

TypeScript

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

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify required attributes
          // (on the delivery vehicle's 'attributes'
          // field) to limit which delivery vehicles
          // are retrieved.
          deliveryVehicleFilterOptions: {
            requiredAttributes: {
              requiredAttribute1: 'foo',
              requiredAttribute2: 'bar',
            },
          },
        });

deliveryVehicleFilterOptions.requiredAttributes specify custom delivery vehicle attributes that are used to filter vehicles displayed on the map. Only vehicles whose attributes include all of the specified key/value pairs are displayed.

locationRestriction limits the area in which to display vehicles on the map. It also controls whether location tracking is active or not. Location tracking will not start until this is set.

Once the location provider is constructed, initialize the map view.

Setting location restriction using the map viewport

The locationRestriction bounds can be configured to match the area currently visible in the map view.

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

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 declarations. 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 Fleet 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'
  }
});

TypeScript

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

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 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 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 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 static MarkerOptions to use
// for the vehicle marker:
vehicleMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    ...
}};

Change vehicle stop icons (planned stops)

You can use custom styling options to configure the icon used to represent vehicle stop locations, the vehicle's stops to be completed. 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 the vehicle stop locations icon.

JavaScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function waypointMarkerSetup({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 successful task markers:
const successfulTaskMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    ...
}};

TypeScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function waypointMarkerSetup(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 successful task markers:
successfulTaskMarkerSetup = {
  markerOptions: {
    opacity: 0.5,
    icon: MY_ICON,
    ...
}};

Add satellite view controls to the map view

The google.maps.Map entity includes controls that users can modify directly. Your map can be customized to include controls that enable satellite view and other map types.

The following example shows how to add satellite view controls to the map view.

JavaScript

// 1. Create a MapView as described above.
this.mapView = new MapView(mapViewOptions);

// 2. Set more options to this mapView.
this.mapView.map.setOptions({
      mapTypeControl: true,
      mapTypeControlOptions: {
         mapTypeIds:    
             [google.maps.MapTypeId.SATELLITE,         
              google.maps.MapTypeId.ROADMAP]
      }
});

TypeScript

// 1. Create a MapView as described above.
this.mapView = new MapView(mapViewOptions);

// 2. Set more options to this mapView.
this.mapView.map.setOptions({
      mapTypeControl: true,
      mapTypeControlOptions: {
         mapTypeIds:    
             [google.maps.MapTypeId.SATELLITE,         
              google.maps.MapTypeId.ROADMAP]
      }
});

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});

// (Assumes a delivery vehicle location provider.)
locationProvider.addListener('update', e => {
  if (e.deliveryVehicle) {
    const distance = 
           e.deliveryVehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next task.`);

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

// (Assumes a delivery vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProviderUpdateEvent) => {
  if (e.deliveryVehicle) {
    const distance = 
           e.deliveryVehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next task.`);

    // 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 when 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

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 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, which includes Fleet Tracking:

  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. Use FleetEngineDeliveryVehicleLocationProvider
  // as appropriate.
  locationProvider = new google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProvider({
    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
  });

mapView.addListener('ready', () => {
  locationProvider.deliveryVehicleId = DELIVERY_VEHICLE_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, which includes Fleet Tracking functionality.
    -->
    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
    </script>
  </body>
</html>

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