W tej sekcji dowiesz się, jak wyświetlić flotę za pomocą biblioteki śledzenia floty w JavaScript. W tych procedurach przyjęto założenie, że biblioteka śledzenia floty została skonfigurowana i załadowano mapę. Szczegółowe informacje znajdziesz w artykule Konfigurowanie biblioteki JavaScript do śledzenia floty.
W tym dokumencie omawiamy te czynności, które możesz wykonać podczas wyświetlania floty:
- Rozpocznij śledzenie floty
- Nasłuchiwanie zdarzeń i obsługa błędów
- Zakończ śledzenie
- Śledzenie pojedynczego pojazdu podczas wyświetlania floty
Rozpocznij śledzenie floty
Aby śledzić flotę, musisz utworzyć instancję dostawcy lokalizacji floty i ustawić ograniczenia lokalizacji dla widocznego obszaru mapy zgodnie z opisem w kolejnych sekcjach.
Utwórz instancję dostawcy lokalizacji floty
Biblioteka śledzenia floty w JavaScript zawiera dostawcę lokalizacji, który pobiera wiele pojazdów z Fleet Engine.
Aby go utworzyć, wykonaj te czynności:
- Użyj identyfikatora projektu oraz odwołania do narzędzia pobierającego tokeny. 
- Użyj zapytania filtra pojazdów Zapytanie filtra pojazdów określa, które pojazdy mają być wyświetlane na mapie. Filtr jest przekazywany do Fleet Engine. - W przypadku usług na żądanie użyj vehicleFilteri zapoznaj się zListVehiclesRequest.filter.
- W przypadku zaplanowanych zadań użyj deliveryVehicleFilteri sprawdźListDeliveryVehiclesRequest.filter
 
- W przypadku usług na żądanie użyj 
- Ustaw obszar ograniczający wyświetlanie pojazdu. Użyj - locationRestriction, aby ograniczyć obszar, w którym mają być wyświetlane pojazdy na mapie. Dopóki nie ustawisz tej opcji, dostawca lokalizacji nie będzie aktywny. Granice lokalizacji możesz ustawić w konstruktorze lub po nim.
- Zainicjuj widok mapy. 
Poniższe przykłady pokazują, jak utworzyć instancję dostawcy lokalizacji floty w przypadku zadań na żądanie i zaplanowanych. Przykłady pokazują też, jak używać pola locationRestriction w konstruktorze, aby aktywować dostawcę lokalizacji.
Przejazdy na żądanie
JavaScript
locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
TypeScript
locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
Zaplanowane zadania
JavaScript
locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
TypeScript
locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
Aby ustawić locationRestriction po konstruktorze, dodaj locationProvider.locationRestriction później w kodzie, jak pokazano w poniższym przykładzie w JavaScript.
   // You can choose to not set locationRestriction in the constructor.
   // In this case, the location provider *DOES NOT START* after this line, because
   // no locationRestriction is set.
   locationProvider = new google.maps.journeySharing.DeliveryFleetLocationProvider({
   ... // not setting locationRestriction here
   });
   // You can then set the locationRestriction *after* the constructor.
   // After this line, the location provider is active.
   locationProvider.locationRestriction = {
     north: 1,
     east: 2,
     south: 0,
     west: 1,
   };
Ustawianie ograniczenia lokalizacji za pomocą widocznego obszaru mapy
Możesz też ustawić locationRestriction granice, aby dopasować je do obszaru widocznego obecnie w widoku mapy.
Przejazdy na żądanie
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;
    }
  });
Zaplanowane zadania
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 provider 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 provider will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });
Inicjowanie widoku mapy
Po utworzeniu dostawcy lokalizacji zainicjuj widok mapy w taki sam sposób, jak w przypadku śledzenia jednego pojazdu.
Po wczytaniu biblioteki JavaScript Journey Sharing zainicjuj widok mapy i dodaj go do strony HTML. Strona powinna zawierać element <div>, który zawiera widok mapy. Element <div> w przykładach poniżej ma nazwę map_canvas.
Przejazdy na żądanie
JavaScript
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});
// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId
                        = 'your-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 want.
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'),
  locationProviders: [locationProvider],
});
// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.VehicleId
                        = 'your-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
Zaplanowane zadania
JavaScript
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});
// 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 want.
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'),
  locationProviders: [locationProvider],
});
// 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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
Nasłuchiwanie zdarzeń i obsługa błędów
Po rozpoczęciu śledzenia floty musisz nasłuchiwać zmian zdarzeń i obsługiwać wszelkie błędy zgodnie z opisem w kolejnych sekcjach.
Nasłuchiwanie zdarzeń zmiany
Możesz pobrać metadane floty z obiektu pojazdu za pomocą dostawcy lokalizacji. Zmiany w metadanych wywołują zdarzenie update. Metadane obejmują właściwości pojazdu, takie jak stan nawigacji, pozostały dystans i atrybuty niestandardowe.
Więcej informacji znajdziesz w tych artykułach:
- Informacje o opcjach pojazdów w przypadku przejazdów na żądanie
- Informacje o opcjach pojazdów w zaplanowanych zadaniach
Poniższe przykłady pokazują, jak nasłuchiwać tych zdarzeń zmiany.
Przejazdy na żądanie
JavaScript
locationProvider.addListener('update', e => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  for (vehicle of e.vehicles) {
    console.log(vehicle.navigationStatus);
  }
});
TypeScript
locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineFleetLocationProviderUpdateEvent) => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  if (e.vehicles) {
    for (vehicle of e.vehicles) {
      console.log(vehicle.navigationStatus);
    }
  }
});
Zaplanowane zadania
JavaScript
locationProvider.addListener('update', e => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});
TypeScript
locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineDeliveryFleetLocationProviderUpdateEvent) => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});
Nasłuchiwanie błędów
Musisz też nasłuchiwać i obsługiwać błędy, które występują podczas śledzenia pojazdu. Błędy, które pojawiają się asynchronicznie podczas przesyłania prośby o informacje o pojeździe, wywołują zdarzenia błędów.
Ten przykład pokazuje, jak nasłuchiwać tych zdarzeń, aby móc obsługiwać błędy.
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);
});
Zakończ śledzenie floty
Aby zatrzymać śledzenie floty, ustaw granice dostawcy lokalizacji na wartość null, a następnie usuń dostawcę lokalizacji z widoku mapy zgodnie z opisem w dalszej części tego artykułu.
Ustaw granice dostawcy lokalizacji na wartość null
Aby dostawca danych o lokalizacji przestał śledzić flotę, ustaw granice dostawcy danych o lokalizacji na wartość null.
Przejazdy na żądanie
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Zaplanowane zadania
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Usuwanie dostawcy lokalizacji z widoku mapy
Poniższy przykład pokazuje, jak usunąć dostawcę lokalizacji z widoku mapy.
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
Śledzenie pojazdu dostawczego podczas wyświetlania floty dostawczej
Jeśli korzystasz z usług mobilności do wykonywania zaplanowanych zadań, możesz wyświetlić flotę i trasę oraz nadchodzące zadania dla konkretnego pojazdu dostawczego w tym samym widoku mapy. Aby to zrobić, utwórz instancje zarówno Delivery Fleet Location Provider, jak i Delivery Vehicle Location Provider i dodaj je do widoku mapy. Po utworzeniu instancji dostawca lokalizacji floty dostawczej zaczyna wyświetlać pojazdy dostawcze na mapie. Poniższe przykłady pokazują, jak utworzyć instancję obu dostawców lokalizacji:
JavaScript
deliveryFleetLocationProvider =
    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 a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});
TypeScript
deliveryFleetLocationProvider =
    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 a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});
Śledzenie pojazdu dostawczego za pomocą dostosowywania znaczników
Aby umożliwić dostawcy lokalizacji pojazdu dostawczego śledzenie pojazdu dostawczego po kliknięciu jego znacznika floty, wykonaj te czynności:
- Dostosuj znacznik i dodaj działanie po kliknięciu. 
- Ukryj znacznik, aby uniknąć duplikatów. 
Przykłady tych kroków znajdziesz w sekcjach poniżej.
Dostosowywanie znacznika i dodawanie działania po kliknięciu
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params: google.maps.journeySharing.DeliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };
Ukrywanie znacznika, aby zapobiec duplikowaniu znaczników
Ukryj marker dostawcy lokalizacji pojazdu dostawczego, aby zapobiec renderowaniu 2 markerów dla tego samego pojazdu:
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params: deliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };