자바스크립트 Fleet 추적 라이브러리로 Fleet 추적

JavaScript Fleet 추적 라이브러리를 사용하면 차량의 위치를 거의 실시간으로 시각화할 수 있습니다. 라이브러리는 Deliveries API를 사용하여 배달 차량과 작업을 시각화합니다. JavaScript 배송 추적 라이브러리와 마찬가지로 이 라이브러리에는 Fleet Engine에 연결하기 위한 표준 google.maps.Map 항목 및 데이터 구성요소를 삽입형으로 대체하는 자바스크립트 지도 구성요소가 포함되어 있습니다.

구성요소

JavaScript Fleet 추적 라이브러리는 배송 차량 및 정류장을 시각화하기 위한 구성요소와 도착예정시간 또는 남은 배달 거리에 대한 원시 데이터 피드를 제공합니다.

차량 추적 지도 보기

차량 추적 지도 보기 구성요소는 차량 및 작업의 위치를 시각화합니다 차량의 경로가 알려진 경우 지도뷰 구성요소는 차량이 예측 경로를 따라 이동할 때 애니메이션을 표시합니다.

차량 추적 지도뷰 예시

위치 정보 제공자

위치 제공업체는 Fleet Engine에 저장된 정보를 사용하여 추적된 객체의 위치 정보를 여정 공유 지도로 전송합니다.

배달 차량 위치 제공업체

배송 차량 위치 제공자는 배송 차량 1대의 위치 정보를 표시합니다. 여기에는 차량 위치 및 배송 차량이 완료한 작업에 관한 정보가 포함됩니다.

차량 위치 제공업체

배송 차량 위치 제공자는 여러 차량의 위치 정보를 표시합니다. 특정 차량 또는 위치를 필터링하거나 전체 Fleet를 표시할 수 있습니다.

추적된 위치의 공개 상태 관리

이 섹션에서는 Fleet Engine 사전 정의된 위치 정보 제공업체에 대한 지도의 추적된 위치 객체에 대한 공개 상태 규칙을 설명합니다. 맞춤 또는 파생 위치 제공자가 공개 상태 규칙을 변경할 수도 있습니다.

배송 차량

배송 차량은 Fleet Engine에서 생성되는 즉시 표시되며 작업과 관계없이 경로 전반에 표시됩니다.

할 일 위치 마커

예정된 차량 정류장은 차량 정류장 마커로 지도에 표시됩니다. 완료된 작업의 마커는 차량에 계획된 정류장과 다른 스타일로 표시됩니다.

작업 결과의 위치는 작업 결과 마커와 함께 표시됩니다. SUCCEEDED 결과가 있는 작업은 성공한 작업 마커와 함께 표시되고, 다른 모든 작업은 실패한 작업 마커와 함께 표시됩니다.

JavaScript Fleet 추적 라이브러리 시작하기

JavaScript Fleet 추적 라이브러리를 사용하기 전에 Fleet Engine을 숙지하고 API 키 가져오기를 숙지해야 합니다. 그런 다음 작업 ID 및 배송 차량 ID 소유권 주장을 만듭니다.

작업 ID 및 배송 차량 ID 소유권 주장 만들기

배달 차량 위치 제공업체를 사용하여 배송 차량을 추적하려면 작업 ID와 배달 차량 ID 클레임이 있는 JSON 웹 토큰 (JWT)을 만듭니다.

JWT 페이로드를 만들려면 승인 섹션에 taskiddeliveryvehicleid 키를 사용하여 추가 클레임을 추가하고 각 키의 값을 *로 설정합니다. 토큰은 Fleet Engine 서비스 수퍼유저 Cloud IAM 역할을 사용하여 만들어야 합니다. 이는 Fleet Engine 항목을 만들고 읽고 수정할 수 있는 광범위한 액세스 권한을 부여하며 신뢰할 수 있는 사용자에게만 공유해야 합니다.

다음 예는 차량 및 작업별로 추적할 토큰을 만드는 방법을 보여줍니다.

{
  "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": "*",
   }
}

인증 토큰 가져오기 프로그램 만들기

인증 토큰 가져오기 프로그램을 만들어 프로젝트의 서비스 계정 인증서를 사용하여 서버에서 적절한 클레임으로 발급된 토큰을 가져올 수 있습니다. 서버에만 토큰을 발급하고 어떤 클라이언트에서도 인증서를 공유하지 않는 것이 중요합니다. 그렇지 않으면 시스템 보안이 침해될 수 있습니다.

가져오기는 프로미스로 래핑된 두 필드가 있는 데이터 구조를 반환해야 합니다.

  • 문자열 token.
  • 숫자 expiresInSeconds입니다. 토큰은 가져온 후 이 시간 내에 만료됩니다.

JavaScript Fleet 추적 라이브러리는 다음 중 하나에 해당하는 경우 인증 토큰 가져오기 프로그램을 통해 토큰을 요청합니다.

  • 새 페이지 로드 시 가져오기 프로그램을 호출하지 않았거나 가져오기 프로그램이 토큰과 함께 반환되지 않은 경우와 같이 유효한 토큰이 없습니다.
  • 이전에 가져온 토큰이 만료되었습니다.
  • 이전에 가져온 토큰이 만료 후 1분 이내입니다.

그 외의 경우 라이브러리는 이전에 발급되었으며 여전히 유효한 토큰을 사용하고 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.expiration_timestamp_ms - Date.now(),
  };
}

토큰 발급을 위해 서버 측 엔드포인트를 구현할 때는 다음 사항에 유의하세요.

  • 엔드포인트는 토큰의 만료 시간을 반환해야 합니다. 위 예시에서는 data.ExpiresInSeconds로 제공됩니다.
  • 다음 예와 같이 인증 토큰 가져오기 프로그램은 만료 시간 (가져온 시간부터 초)을 라이브러리에 전달해야 합니다.
  • SERVER_TOKEN_URL은 백엔드 구현에 따라 다르며 샘플 앱 백엔드의 URL입니다.
    • https://SERVER_URL/token/delivery_driver/DELIVERY_VEHICLE_ID
    • https://SERVER_URL/token/delivery_consumer/TRACKING_ID
    • https://SERVER_URL/token/fleet_reader

HTML에서 지도 로드

다음 예는 지정된 URL에서 JavaScript 여정 공유 라이브러리를 로드하는 방법을 보여줍니다. 콜백 매개변수는 API가 로드된 후 initMap 함수를 실행합니다. defer 속성을 사용하면 API가 로드되는 동안 브라우저가 페이지의 나머지 부분을 계속 렌더링합니다.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>

배송 차량 따라가기

이 섹션에서는 JavaScript Fleet 추적 라이브러리를 사용하여 배송 차량을 추적하는 방법을 보여줍니다. 코드를 실행하기 전에 스크립트 태그에 지정된 콜백 함수에서 라이브러리를 로드해야 합니다.

배송 차량 위치 제공자 인스턴스화

JavaScript Fleet 추적 라이브러리는 Fleet Engine Deliveries API의 위치 제공자를 사전 정의합니다. 프로젝트 ID와 토큰 팩토리 참조를 사용하여 인스턴스화하세요.

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

지도뷰 초기화

JavaScript 여정 공유 라이브러리를 로드한 후 지도 뷰를 초기화하고 HTML 페이지에 추가합니다. 페이지에는 지도뷰를 포함하는 <div> 요소가 포함되어야 합니다. 아래 예에서 <div> 요소의 이름은 map_canvas입니다.

JavaScript

const mapView = new 
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'), 
  locationProviders: [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'),
  locationProviders: [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);

변경 이벤트 수신 대기

위치 제공자를 사용하여 deliveryVehicle 객체에서 작업에 관한 메타 정보를 검색할 수 있습니다. 메타 정보에는 도착예정시간과 다음 차량 승차 또는 하차 전까지 남은 거리가 포함됩니다. 메타 정보를 변경하면 update 이벤트가 트리거됩니다. 다음 예는 이러한 변경 이벤트를 수신 대기하는 방법을 보여줍니다.

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

오류 수신 대기

배달 차량 정보를 요청하여 비동기식으로 발생하는 오류는 오류 이벤트를 트리거합니다. 다음 예는 오류를 처리하기 위해 이러한 이벤트를 수신 대기하는 방법을 보여줍니다.

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

추적 중지

위치 정보 제공업체에서 배송 차량을 추적하지 못하도록 하려면 위치 정보 제공업체에서 배송 차량 ID를 삭제합니다.

JavaScript

locationProvider.deliveryVehicleId = '';

TypeScript

locationProvider.deliveryVehicleId = '';

지도뷰에서 위치 제공자 삭제

다음 예는 지도뷰에서 위치 제공업체를 삭제하는 방법을 보여줍니다.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

배포 Fleet 보기

이 섹션에서는 JavaScript 여정 공유 라이브러리를 사용하여 전송 Fleet를 확인하는 방법을 보여줍니다. 코드를 실행하기 전에 스크립트 태그에 지정된 콜백 함수에서 라이브러리를 로드해야 합니다.

배송 차량 위치 제공자 인스턴스화

JavaScript Fleet 추적 라이브러리는 FleetEngine Deliveries API에서 여러 차량을 가져오는 위치 제공업체를 미리 정의합니다. 프로젝트 ID와 토큰 가져오기 프로그램에 대한 참조를 사용하여 인스턴스화합니다.

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 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 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"',
        });

deliveryVehicleFilter는 지도에 표시된 차량을 필터링하는 데 사용되는 쿼리를 지정합니다. 이 필터는 Fleet Engine으로 직접 전달됩니다. 지원되는 형식은 ListDeliveryVehiclesRequest.filter를 참고하세요.

locationRestriction은 지도에 차량을 표시할 영역을 제한합니다. 또한 위치 추적의 활성화 여부도 제어합니다. 위치 추적은 설정될 때까지 시작되지 않습니다.

위치 제공자가 생성되면 지도 뷰를 초기화하세요.

지도 표시 영역을 사용하여 위치 제한 설정

locationRestriction 경계는 지도뷰에 현재 표시된 영역과 일치하도록 구성할 수 있습니다.

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

변경 이벤트 수신 대기

위치 제공자를 사용하여 deliveryVehicles 객체에서 Fleet에 대한 메타 정보를 검색할 수 있습니다. 메타 정보에는 내비게이션 상태, 남은 거리, 맞춤 속성과 같은 차량 속성이 포함됩니다. 자세한 내용은 참조 문서를 참고하세요. 메타 정보를 변경하면 update 이벤트가 트리거됩니다. 다음 예는 이러한 변경 이벤트를 수신 대기하는 방법을 보여줍니다.

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

오류 수신 대기

전송 Fleet 정보 요청으로부터 비동기식으로 발생하는 오류는 오류 이벤트를 트리거합니다. 이러한 이벤트를 수신 대기하는 방법의 예는 오류 수신 대기를 참고하세요.

추적 중지

위치 제공업체가 배송 차량을 추적하지 못하도록 하려면 위치 제공업체의 경계를 null로 설정합니다.

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

지도뷰에서 위치 제공자 삭제

다음 예는 지도뷰에서 위치 제공업체를 삭제하는 방법을 보여줍니다.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

배송 차량을 추적하고 운송 차량을 추적하세요

차량을 보면서 특정 배달 차량의 경로와 예정된 작업을 표시할 수 있습니다. 이렇게 하려면 배송 차량 위치 제공업체와 배달 차량 위치 제공업체를 모두 인스턴스화하고 둘 다 지도 뷰에 추가합니다.

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

배송 차량 위치 제공자가 지도에 배송 차량을 표시하기 시작합니다. 마커 맞춤설정을 사용하여 차량 마커를 클릭하면 배달 차량 위치 제공자가 배송 차량을 추적할 수 있습니다.

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

동일한 차량에 두 개의 마커가 렌더링되지 않도록 배달 차량 위치 정보 제공자에서 마커를 숨깁니다.

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

기본 지도의 디자인 맞춤설정

지도 구성요소의 디자인을 맞춤설정하려면 클라우드 기반 도구를 사용하거나 코드에서 직접 옵션을 설정하여 지도 스타일을 지정합니다.

클라우드 기반 지도 스타일 지정 사용

클라우드 기반 지도 스타일 지정을 사용하면 코드를 변경하지 않고도 Google Cloud 콘솔에서 Google 지도를 사용하는 모든 앱의 지도 스타일을 만들고 수정할 수 있습니다. 지도 스타일은 Cloud 프로젝트에 지도 ID로 저장됩니다. JavaScript Fleet 추적 지도에 스타일을 적용하려면 JourneySharingMapView를 만들 때 mapId를 지정합니다. JourneySharingMapView가 인스턴스화된 후에는 mapId 필드를 변경하거나 추가할 수 없습니다. 다음 예는 지도 ID를 사용하여 이전에 만든 지도 스타일을 사용 설정하는 방법을 보여줍니다.

JavaScript

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

TypeScript

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

코드 기반 지도 스타일 지정 사용

지도 스타일을 맞춤설정하는 또 다른 방법은 JourneySharingMapView를 만들 때 mapOptions를 설정하는 것입니다.

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

마커 맞춤설정 사용

JavaScript Fleet 추적 라이브러리를 사용하면 지도에 추가된 마커의 디자인과 분위기를 맞춤설정할 수 있습니다. 마커 맞춤설정을 지정하면 됩니다. 그러면 Fleet 추적 라이브러리가 마커를 지도에 추가하기 전에 그리고 마커를 업데이트할 때마다 적용합니다.

가장 간단한 맞춤설정은 같은 유형의 모든 마커에 적용될 MarkerOptions 객체를 지정하는 것입니다. 객체에 지정된 변경사항은 각 마커가 생성된 후 적용되며 모든 기본 옵션을 덮어씁니다.

고급 옵션은 맞춤설정 함수를 지정하는 것입니다. 맞춤설정 함수를 사용하면 데이터를 기반으로 마커의 스타일을 지정할 수 있을 뿐만 아니라 마커에 클릭 처리와 같은 상호작용을 추가할 수 있습니다. 특히 차량 추적은 마커가 나타내는 객체 유형(차량, 정류장, 작업)에 대한 데이터를 맞춤설정 함수에 전달합니다. 이렇게 하면 마커 요소 자체의 현재 상태(예: 남은 정류장 수 또는 작업 유형)에 따라 마커 스타일을 변경할 수 있습니다. Fleet Engine 외부 소스의 데이터에 대해 조인하고 해당 정보를 기반으로 마커의 스타일을 지정할 수도 있습니다.

또한 맞춤설정 함수를 사용하여 마커 표시 여부를 필터링할 수 있습니다. 이렇게 하려면 마커에서 setVisible(false)를 호출합니다.

그러나 성능상의 이유로 FleetEngineDeliveryFleetLocationProvider.deliveryVehicleFilter와 같은 위치 제공자에서 네이티브 필터링을 사용하여 필터링하는 것이 좋습니다. 하지만 추가 필터링 기능이 필요한 경우 맞춤설정 기능을 사용하여 필터링을 적용할 수 있습니다.

Fleet 추적 라이브러리는 다음과 같은 맞춤설정 매개변수를 제공합니다.

MarkerOptions을 사용하여 마커의 스타일 변경

다음 예에서는 MarkerOptions 객체를 사용하여 차량 마커의 스타일을 구성하는 방법을 보여줍니다. 위에 나열된 마커 맞춤설정 매개변수를 사용하여 마커의 스타일을 맞춤설정하려면 이 패턴을 따르세요.

JavaScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

맞춤설정 기능을 사용하여 마커의 스타일 변경

다음 예는 차량 마커의 스타일을 구성하는 방법을 보여줍니다. 위에 나열된 마커 맞춤설정 매개변수를 사용하여 마커의 스타일을 맞춤설정하려면 이 패턴을 따르세요.

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    params.marker.setLabel(`${stopsLeft}`);
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    params.marker.setLabel(`${stopsLeft}`);
  };

마커에 클릭 처리 추가

다음 예는 차량 마커에 클릭 처리를 추가하는 방법을 보여줍니다. 위에 나열된 마커 맞춤설정 매개변수를 사용하여 마커에 클릭 처리를 추가하려면 다음 패턴을 따르세요.

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // Perform desired action.
      });
    }
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // Perform desired action.
      });
    }
  };

표시되는 마커 필터링

다음 예는 표시되는 차량 마커를 필터링하는 방법을 보여줍니다. 위에 나열된 마커 맞춤설정 매개변수를 사용하여 마커를 필터링하려면 이 패턴을 따르세요.

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    if (stopsLeft > 10) {
      params.marker.setVisible(false);
    }
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    if (stopsLeft > 10) {
      params.marker.setVisible(false);
    }
  };

배달 차량을 따라갈 때 다중선 맞춤설정 사용

JavaScript Fleet 추적 라이브러리를 사용하면 지도에서 따라가는 차량 경로의 디자인과 분위기를 맞춤설정할 수도 있습니다. 라이브러리는 차량의 활성 또는 남은 경로에 있는 각 좌표 쌍의 google.maps.Polyline 객체를 만듭니다. 다중선 맞춤설정을 지정하여 Polyline 객체의 스타일을 지정할 수 있습니다. 그런 다음 라이브러리는 객체를 지도에 추가하기 전과 객체에 사용된 데이터가 변경된 경우, 두 가지 상황에서 맞춤설정을 적용합니다.

마커 맞춤설정과 마찬가지로, PolylineOptions 집합을 지정하여 객체를 만들거나 업데이트할 때 일치하는 모든 Polyline 객체에 적용할 수 있습니다.

마찬가지로 맞춤설정 기능을 지정할 수 있습니다. 맞춤설정 함수를 사용하면 Fleet Engine에서 전송한 데이터를 기반으로 객체의 개별 스타일을 지정할 수 있습니다. 이 함수는 현재 차량 상태에 따라 각 객체의 스타일을 변경할 수 있습니다. 예를 들어 Polyline 객체에 더 깊은 음영을 지정하거나 차량이 느리게 이동할 때 더 두꺼워지게 합니다. Fleet Engine 외부 소스에서 조인하고 해당 정보를 기반으로 Polyline 객체의 스타일을 지정할 수도 있습니다.

FleetEngineDeliveryVehicleLocationProviderOptions에 제공된 매개변수를 사용하여 맞춤설정을 지정할 수 있습니다. 차량 이동 과정에서 이미 이동, 주행 중, 아직 이동하지 않음 등 다양한 경로 상태에 대한 맞춤설정을 설정할 수 있습니다. 매개변수는 다음과 같습니다.

PolylineOptions를 사용하여 Polyline 객체의 스타일 지정 변경

다음 예는 PolylineOptions를 사용하여 Polyline 객체의 스타일을 구성하는 방법을 보여줍니다. 위에 나열된 다중선 맞춤설정을 사용하여 Polyline 객체의 스타일을 맞춤설정하려면 이 패턴을 따르세요.

JavaScript

activePolylineCustomization = {
  strokeWidth: 5,
  strokeColor: 'black',
};

TypeScript

activePolylineCustomization = {
  strokeWidth: 5,
  strokeColor: 'black',
};

맞춤설정 함수를 사용하여 Polyline 객체의 스타일 지정 변경

다음 예에서는 맞춤설정 함수를 사용하여 활성 다중선 객체의 스타일을 구성하는 방법을 보여줍니다. 앞에서 나열한 다중선 맞춤설정 매개변수를 사용하여 Polyline 객체의 스타일을 맞춤설정하려면 이 패턴을 따르세요.

JavaScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params) => {
    const distance = params.deliveryVehicle.remainingDistanceMeters;
    if (distance < 1000) {

      // params.polylines contains an ordered list of Polyline objects for
      // the path.
      for (const polylineObject of params.polylines) {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

TypeScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params: DeliveryVehiclePolylineCustomizationFunctionParams) => {
    const distance = params.deliveryVehicle.remainingDistanceMeters;
    if (distance < 1000) {

      // params.polylines contains an ordered list of Polyline objects for
      // the path.
      for (const polylineObject of params.polylines) {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

Polyline 객체의 공개 상태 제어

기본적으로 모든 Polyline 객체가 표시됩니다. Polyline 객체를 보이지 않게 하려면 다음과 같이 visible 속성을 설정하세요.

JavaScript

remainingPolylineCustomization = {visible: false};

TypeScript

remainingPolylineCustomization = {visible: false};

차량 또는 위치 마커의 InfoWindow 표시

InfoWindow를 사용하여 차량 또는 위치 마커에 대한 추가 정보를 표시할 수 있습니다.

다음 예에서는 InfoWindow를 만들어 차량 마커에 연결하는 방법을 보여줍니다.

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

자동 맞춤 사용 중지

자동 맞추기를 사용 중지하여 지도가 차량 및 예상 경로에 표시 영역 자동으로 맞지 않도록 할 수 있습니다. 다음 예에서는 여정 공유 지도뷰를 구성할 때 자동 맞추기를 사용 중지하는 방법을 보여줍니다.

JavaScript

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

TypeScript

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

기존 지도 바꾸기

마커 또는 기타 맞춤설정이 포함된 기존 지도를 대체해도 맞춤설정이 그대로 유지됩니다.

예를 들어 마커가 표시되는 표준 google.maps.Map 항목이 포함된 웹페이지가 있다고 가정해 보겠습니다.

<!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>

Fleet 추적이 포함된 JavaScript 여정 공유 라이브러리를 추가하려면 다음 안내를 따르세요.

  1. 인증 토큰 팩토리의 코드를 추가합니다.
  2. initMap() 함수에서 위치 제공자를 초기화합니다.
  3. initMap() 함수에서 지도뷰를 초기화합니다. 뷰에는 지도가 포함됩니다.
  4. 맞춤설정을 지도뷰 초기화를 위한 콜백 함수로 이동합니다.
  5. API 로더에 위치 라이브러리를 추가합니다.

다음 예는 적용해야 할 변경사항을 보여줍니다.

<!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'),
    locationProviders: [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>

울루루 근처에서 지정된 ID로 배송 차량을 운전하는 경우 이제 지도에 렌더링됩니다.