Wyświetlanie floty

Ta sekcja pokazuje, jak korzystać z biblioteki śledzenia floty JavaScript aby wyświetlić flotę. W tych procedurach przyjęto, że flota została skonfigurowana śledzenia biblioteki i wczytała mapę. Więcej informacji: Skonfiguruj bibliotekę śledzenia floty JavaScript.

W tym dokumencie omówiono następujące czynności, które można zrobić, wyświetlając flota:

  1. Zacznij śledzić flotę.
  2. Wykrywaj zdarzenia i obsługuj błędy.
  3. Przestań śledzić.
  4. Śledź 1 pojazd podczas wyświetlania floty.

Zacznij śledzić flotę

Aby śledzić flotę, musisz utworzyć instancję dostawcy lokalizacji floty ustawić ograniczenia lokalizacji dla widocznego obszaru mapy w sposób opisany w następujących sekcji.

Utwórz instancję dostawcy lokalizacji floty

Biblioteka śledzenia floty JavaScript zawiera dostawcę lokalizacji, który pobiera wiele pojazdów z Fleet Engine.

Aby utworzyć jej instancję, wykonaj te czynności:

  1. Użyj identyfikatora projektu, a także odniesienia do modułu pobierania tokenów.

  2. Użyj zapytania filtra pojazdów Zapytanie filtra pojazdów określa, które pojazdów dostępnych na mapie. Filtr jest przekazywany do Fleet Engine.

  3. Ustaw granice dla wyświetlania pojazdu. locationRestriction – do ograniczyć obszar, na którym pojazdy są wyświetlane na mapie. Lokalizacja dostawca nie jest aktywny, dopóki to ustawienie nie zostanie skonfigurowane. Granice lokalizacji możesz ustawić na w konstruktorze lub za konstruktorem.

  4. Zainicjuj widok mapy.

Poniższe przykłady pokazują, jak utworzyć instancję dostawcy lokalizacji floty dla w ramach zadań na żądanie i zaplanowanych zadań. Te przykłady pokazują również, jak korzystać locationRestriction w konstruktorze, by ustawić dostawcę lokalizacji aktywne.

Podróże 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 za konstruktorem, dodaj funkcję locationProvider.locationRestriction później w kodzie jako w poniższym przykładzie JavaScriptu.

   // 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 ograniczeń lokalizacji w widoku mapy

Możesz też ustawić granice locationRestriction, aby pasowały do obecnego obszaru widoczne w widoku mapy.

Podróże 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 tym samym co robimy, gdy podążamy za jednym pojazdem.

Po wczytaniu biblioteki udostępniania czynności JavaScript zainicjuj ją. widok mapy i dodać go do strony HTML. Strona powinna zawierać element <div> zawierający widok mapy. Element <div> w poniższych przykładach ma nazwę map_canvas.=

Podróże 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);

Wykrywaj zdarzenia i obsługuj błędy

Gdy zaczniesz obserwować flotę, musisz nasłuchiwać zmian zdarzeń i eliminować ewentualne błędy w sposób opisany w dalszej części tego artykułu.

Wykrywaj zdarzenia zmian

Możesz pobrać metainformacje o flocie z obiektu pojazdu za pomocą z dostawcą lokalizacji. Zmiany metadanych powodują aktualizację . Metadane obejmują właściwości pojazdu, takie jak nawigacja stan, odległość i atrybuty niestandardowe.

Szczegółowe informacje można znaleźć w następujących dokumentach:

W przykładach poniżej pokazujemy, jak wsłuchiwać się w zdarzenia zmian.

Podróże 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);
    }
  }
});

Wykrywaj błędy

Przyda Ci się też wykrywanie błędów, które wystąpiły przy pojazdu. Błędy, które występują asynchronicznie podczas wysyłania żądania dotyczącego pojazdu zdarzeń błędów związanych z wyświetlaniem informacji.

Poniższy przykład pokazuje, jak nasłuchiwać aby móc naprawić 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);
});

Przestań śledzić flotę

Aby zatrzymać śledzenie floty, ustaw granice dostawcy lokalizacji na wartość null, a następnie usunąć dostawcę lokalizacji z widoku mapy w sposób opisany w kolejnych sekcjach.

Ustaw granice dostawcy lokalizacji na wartość null

Aby uniemożliwić dostawcy lokalizacji śledzenie floty, wyznacz granice dostawcy lokalizacji na null.

Podróże na żądanie

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Zaplanowane zadania

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Usuń dostawcę lokalizacji z widoku mapy

Poniższy przykład pokazuje, jak usunąć dostawcę lokalizacji z widoku mapy.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Śledź pojazd dostawczy, wyświetlając flotę dostawczą

Jeśli używasz usług mobilnych do zaplanowanych zadań, możesz wyświetlić flotę i wyświetlanie trasy oraz nadchodzących zadań dla konkretnego pojazdu dostawczego. w tym samym widoku mapy. Aby to zrobić, utwórz instancję zarówno lokalizacji floty dostarczania, Dostawca i dostawcę lokalizacji pojazdu dostarczanego przez firmę kurierską oraz dodaj ich do mapy. widok. Po utworzeniu wystąpienia dostawca lokalizacji floty urządzeń zacznie się wyświetlać pojazdów dostawczych na mapie. Poniższe przykłady pokazują, jak utworzyć instancję obaj dostawcy 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
});

Śledź pojazd dostawczy, korzystając z dostosowania znacznika

Aby umożliwić dostawcy lokalizacji pojazdu dostawy śledzenie pojazdu dostawy po kliknięciu znacznika floty wykonaj te czynności:

  1. Dostosuj znacznik i dodaj działanie kliknięcia.

  2. Ukryj znacznik, aby zapobiec jego duplikowaniu.

Przykłady takich czynności znajdziesz w sekcjach poniżej.

Dostosowywanie znacznika i dodawanie działania kliknięcia

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

Ukryj znacznik, aby zapobiec jego duplikowaniu

Ukryj znacznik u dostawcy lokalizacji pojazdu dostawy, aby zapobiec renderowaniu dwa znaczniki 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);
    }
  };

Co dalej?