Wyświetlanie floty

W tej sekcji dowiesz się, jak wyświetlić flotę za pomocą biblioteki JavaScript do śledzenia floty. W tych procedurach zakładamy, że masz skonfigurowaną bibliotekę do śledzenia floty i załadowaną mapę. Więcej informacji znajdziesz w artykule Konfigurowanie biblioteki JavaScript do śledzenia floty.

Z tego dokumentu dowiesz się, co możesz zrobić podczas wyświetlania floty:

  1. Rozpocznij śledzenie floty.
  2. Nasłuchuj zdarzeń i obsługuj błędy.
  3. Zatrzymaj śledzenie.
  4. Śledź pojedynczy pojazd 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 JavaScript do śledzenia floty zawiera dostawcę lokalizacji, który pobiera wiele pojazdów z Fleet Engine.

Aby utworzyć jego instancję:

  1. Użyj identyfikatora projektu oraz odwołania do narzędzia do pobierania tokenów.

  2. Użyj zapytania filtra pojazdów. Zapytanie filtra pojazdów określa, które pojazdy są wyświetlane na mapie. Filtr jest przekazywany do Fleet Engine.

  3. Ustaw obszar ograniczający wyświetlanie pojazdów. Użyj locationRestriction, aby ograniczyć obszar, w którym mają być wyświetlane pojazdy na mapie. Dostawca lokalizacji jest aktywny dopiero po ustawieniu tego parametru. Granice lokalizacji możesz ustawić w konstruktorze lub po nim.

  4. Zainicjuj widok mapy.

Poniższe przykłady pokazują, jak utworzyć instancję dostawcy lokalizacji floty w przypadku usług na żądanie i zaplanowanych zadań. Pokazują też, jak użyć 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 w dalszej części kodu, jak pokazano w tym przykładzie 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ć granice locationRestriction, aby odpowiadały obszarowi widocznemu 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 pojedynczego 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. W poniższych przykładach element <div> 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

Za pomocą dostawcy lokalizacji możesz pobierać metadane o flocie z obiektu pojazdu. Zmiany 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:

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 występują asynchronicznie podczas wysyłania prośby o informacje o pojeździe, wywołują zdarzenia błędu.

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

Zatrzymywanie śledzenia floty

Aby zatrzymać śledzenie floty, ustaw granice dostawcy lokalizacji na null, a następnie usuń dostawcę lokalizacji z widoku mapy zgodnie z opisem w kolejnych sekcjach.

Ustawianie granic dostawcy lokalizacji na null

Aby dostawca lokalizacji przestał śledzić flotę, ustaw jego granice na 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

Ten 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 używasz usług mobilnych do zaplanowanych zadań, możesz wyświetlać flotę oraz trasę i nadchodzące zadania dla konkretnego pojazdu dostawczego w tym samym widoku mapy. Aby to zrobić, utwórz instancję dostawcy lokalizacji floty dostawczej i dostawcy lokalizacji pojazdu dostawczego, a następnie dodaj je do widoku mapy. Po utworzeniu instancji dostawca lokalizacji floty dostawczej zacznie 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ą dostosowania znacznika

Aby dostawca lokalizacji pojazdu dostawczego mógł śledzić pojazd dostawczy po kliknięciu jego znacznika floty, wykonaj te czynności:

  1. Dostosuj znacznik i dodaj działanie po kliknięciu.

  2. Ukryj znacznik, aby uniknąć duplikatów.

Przykłady tych czynności znajdziesz w kolejnych sekcjach.

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 uniknąć duplikatów

Ukryj znacznik dostawcy lokalizacji pojazdu dostawczego, aby uniknąć renderowania 2 znaczników 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);
    }
  };

Co dalej?