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

JavaScript Fleet 추적 라이브러리를 사용하면 클러스터의 위치를 시각화하여 구축합니다. 라이브러리는 On Demand를 사용하여 차량 공유 및 배송 API 을 사용하면 차량과 이동을 시각화할 수 있습니다. JavaScript Fleet 추적 라이브러리에는 드롭인인 JavaScript 지도 구성요소가 포함되어 있습니다. 표준 google.maps.Map 항목 및 데이터 구성요소를 대체하여 연결할 수 있습니다

구성요소

JavaScript Fleet 추적 라이브러리는 다음을 시각화하기 위한 구성요소를 제공합니다. 도착예정시간 또는 남은 시간에 대한 원시 데이터 피드와 함께 거리를 지정할 수 있습니다.

차량 추적 지도뷰

차량 추적 지도뷰 구성요소는 차량의 위치를 시각화하고 있습니다. 차량의 경로를 알고 있는 경우 지도뷰 구성요소는 는 예상 경로를 따라 이동하는 차량에 애니메이션을 적용합니다.

차량 추적 지도뷰
예시

위치 정보 제공자

위치 정보 제공자는 위치를 전송하기 위해 Fleet Engine에 저장된 정보와 함께 작동합니다. 여행 공유 지도에 추적된 객체의 정보를 저장합니다.

차량 위치 정보 제공자

차량 위치 정보 제공자는 단일 차량의 위치 정보를 표시합니다. 여기에는 있습니다.

Fleet 위치 제공업체

차량 위치 제공업체는 여러 차량의 위치 정보를 표시합니다. 특정 차량 및 차량 위치를 표시하도록 필터링하거나 전체 Fleet의 차량 위치를 표시합니다.

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

공개 상태 규칙에 따라 추적된 위치 객체가 지도에 표시되는 시점이 결정됩니다. Fleet Engine 위치 제공업체용입니다. 참고 - 맞춤 위치 또는 파생 위치 사용 제공자는 공개 상태 규칙을 변경할 수 있습니다.

차량

차량은 Fleet Engine에서 생성되는 즉시 표시되며 표시됩니다. 차량_상태가 Online인 경우. 즉, 차량이 눈에 잘 띄도록 차량에 할당된 현재 이동이 없는 경우

경유지 위치 마커

경유지 위치 마커는 차량 이동을 시작하는 지점을 나타냅니다. 도착지로 끝나고 도착지로 끝납니다. 경유지 위치 마커는 다음과 같이 정의할 수 있습니다.

  • 출발지: 차량 이동의 시작 위치를 나타냅니다.
  • 중간: 차량 이동의 중간 기착을 나타냅니다.
  • 목적지 - 차량 이동의 최종 위치를 나타냅니다.

계획된 차량 경유지는 지도에 출발지, 중간 및 중거리로 표시됩니다. 대상 마커입니다.

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

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

이동 ID 및 차량 ID 소유권 주장 만들기

차량 위치를 사용하여 차량 추적 provider의 경우 이동으로 JSON 웹 토큰 (JWT)을 만듭니다. 신분증 및 차량 ID 소유권 주장

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

다음 예는 차량별 추적용 토큰을 만드는 방법과 태스크:

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

인증 토큰 가져오기 도구 만들기

JavaScript Fleet 추적 라이브러리는 인증을 사용하여 토큰을 요청합니다. 다음 중 하나가 참일 때 토큰 가져오기 도구를 사용할 수 있습니다.

  • 유효한 토큰이 없는 경우(예: 가져오기 도구를 호출하지 않은 경우) 가져올 수 있는 정보를 반환하는지 확인할 수 있습니다.
  • 이전에 가져온 토큰이 만료되었습니다.
  • 이전에 가져온 토큰이 만료 후 1분 이내에 있습니다.

그렇지 않으면 라이브러리는 이전에 발행된 여전히 유효한 토큰을 사용하고 가져올 수 없습니다

인증 토큰 가져오기 프로그램을 만들면 다음으로 생성된 토큰을 가져올 수 있습니다. 적절한 클레임을 요청할 수 있습니다. 사용할 수 있습니다 이 페이지에서만 토큰을 만드는 것이 어떠한 클라이언트에서도 인증서를 공유하지 않습니다. 그렇지 않은 경우 시스템의 보안을 침해할 수 있습니다.

가져오기 프로그램은 반드시 구조 두 개의 필드로 구성되며 프로미스로 래핑됩니다.

  • 문자열 token.
  • 숫자 expiresInSeconds입니다. 토큰은 가져올 수 있습니다.

다음 예시에서는 인증 토큰 가져오기 프로그램을 만드는 방법을 보여줍니다.

자바스크립트

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: <ph type="x-smartling-placeholder">
      </ph>
    • https://SERVER_URL/token/driver/VEHICLE_ID
    • https://SERVER_URL/token/consumer/TRIP_ID
    • https://SERVER_URL/token/fleet_reader

HTML에서 지도 로드

다음 예는 JavaScript Journey 공유 라이브러리를 로드하는 방법을 보여줍니다. 가져올 수 있습니다. 콜백 매개변수는 initMap 함수를 실행합니다. API를 로드한 후에 구현됩니다. defer 속성을 사용하면 브라우저에서 렌더링을 계속할 수 있습니다. 페이지의 나머지 부분과 일치해야 합니다

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

차량 따라가기

이 섹션에서는 JavaScript Fleet 추적 라이브러리를 사용하여 있습니다. 여기에 지정된 콜백 함수에서 라이브러리를 로드했는지 확인합니다. 스크립트 태그를 해야 합니다.

차량 위치 정보 제공자 인스턴스화

JavaScript Fleet 추적 라이브러리는 On Demand Rides and Deliveries API입니다. 프로젝트 ID 및 토큰 팩토리를 사용하여 인스턴스화합니다.

자바스크립트

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

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

TypeScript

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

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

지도뷰 초기화

JavaScript Journey 공유 라이브러리를 로드한 후 지도뷰 초기화 HTML 페이지에 추가합니다. 페이지에는 &lt;div&gt; 요소가 포함되어야 합니다. 지도뷰를 포함하는 3개 광고 소재입니다. &lt;div&gt; 요소의 이름은 &lt;div&gt;로 지정되며 참조하세요.

자바스크립트

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 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 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.
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// 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 wish.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

변경 이벤트 수신 대기

vehicle 객체에서 차량에 관한 메타 정보를 가져올 수 있습니다. 위치 정보 제공자를 사용합니다. 메타 정보에는 도착예정시간과 차량의 다음 승차 또는 하차 지점까지의 거리 메타 변경사항 정보는 update 이벤트를 트리거합니다. 다음 예는 수신 대기 방법을 보여줍니다. 적용할 수 있습니다

자바스크립트

locationProvider.addListener('update', e => {
  // e.vehicle contains data that may be
  // useful to the rest of the UI.
  if (e.vehicle) {
    console.log(e.vehicle.vehicleState);
  }
});

TypeScript

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

오류 수신 대기

차량 정보 요청 시 비동기식으로 발생하는 오류 트리거 오류 이벤트입니다. 다음 예는 다음 위치에서 이러한 이벤트를 수신 대기하는 방법을 보여줍니다. 몇 가지 기본 기능에 대해 알아보겠습니다

자바스크립트

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를 삭제하세요. 제공합니다.

자바스크립트

locationProvider.vehicleId = '';

TypeScript

locationProvider.vehicleId = '';

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

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

자바스크립트

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

차량 Fleet 보기

이 섹션에서는 JavaScript Journey 공유 라이브러리를 사용하여 있습니다 콜백 함수에서 라이브러리를 로드해야 합니다. 지정해야 합니다.

차량 위치 정보 제공자 인스턴스화

JavaScript Fleet 추적 라이브러리는 On Demand Rides and Deliveries API에서 여러 차량을 가져옵니다. 사용 인스턴스화할 토큰 가져오기 프로그램에 대한 참조 및 프로젝트 ID

자바스크립트

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

vehicleFilter는 지도에 표시된 차량을 필터링하는 데 사용되는 쿼리를 지정합니다. 이 필터는 Fleet Engine에 직접 전달됩니다. 자세한 내용은 ListVehiclesRequest 참조하세요.

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

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

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

locationRestriction 경계는 다음에 표시되는 영역과 일치하도록 구성할 수 있습니다. 표시됩니다.

자바스크립트

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

변경 이벤트 수신 대기

vehicles 객체에서 Fleet에 대한 메타 정보를 검색할 수 있습니다. 위치 정보 제공자를 사용합니다. 메타 정보에 차량 속성이 포함됨 내비게이션 상태, 다음 경유지까지의 거리, 맞춤 속성 등 보기 참조 문서 를 참조하세요. 메타 정보가 변경되면 업데이트 이벤트가 트리거됩니다. 이 다음 예는 이러한 변경 이벤트를 수신 대기하는 방법을 보여줍니다.

자바스크립트

locationProvider.addListener('update', e => {
  // 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);
    }
  }
});

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

오류 수신 대기

차량 정보 요청 시 비동기식으로 발생하는 오류 오류 이벤트를 트리거합니다. 이러한 이벤트를 수신 대기하는 방법을 보여주는 예시는 다음을 참고하세요. 오류 수신 대기를 참고하세요.

추적 중지

위치 정보 제공자가 Fleet를 추적하지 못하게 하려면 위치 제공자를 null로 설정합니다.

자바스크립트

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

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

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

자바스크립트

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

지도 구성요소의 디자인을 맞춤설정하려면 지도를 사용하여 코드 내에서 직접 옵션을 설정하여 사용할 수 있습니다.

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

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

자바스크립트

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

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

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

자바스크립트

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 추적 라이브러리를 사용하면 디자인과 분위기를 맞춤설정할 수 있습니다. 개의 마커가 표시됩니다. 이렇게 하려면 마커 맞춤설정을 지정하고 차량 추적 라이브러리에서 마커를 지도에 추가하기 전에 마커를 업데이트할 때마다 말이죠

원하는 경우 라벨을 지정하여 MarkerOptions 객체를 사용하여 동일한 유형의 모든 마커에 적용합니다. 객체는 각 마커가 생성된 후에 적용되어 기본값을 덮어씁니다. 있습니다.

고급 옵션으로 맞춤설정 기능을 지정할 수 있습니다. 맞춤설정 기능을 사용하면 데이터에 따라 마커의 스타일을 지정할 수도 있습니다. 마커에 상호작용 추가(예: 클릭 처리) 구체적으로 Fleet 추적은 추적 중인 객체 유형에 대한 데이터를 맞춤설정 함수에 마커는 차량, 정류장 또는 작업을 나타냅니다. 그러면 마커 스타일을 사용하여 마커 요소 자체의 현재 상태에 따라 변경됩니다. 예를 들어 남은 중지 횟수 또는 태스크 유형 또한 이 정보를 기반으로 마커의 스타일을 지정할 수 있습니다

또한 맞춤설정 함수를 사용하여 마커 가시성을 필터링할 수 있습니다. 이렇게 하려면 다음을 호출합니다. setVisible(false) 을 클릭합니다.

하지만 성능상의 이유로 네이티브 광고로 필터링하는 것이 좋습니다. 위치 정보 제공자에서의 필터링(예: FleetEngineFleetLocationProvider.vehicleFilter 즉, 추가적인 필터링 기능이 필요한 경우 데이터를 필터링할 수 있습니다.

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

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

다음 예는 MarkerOptions 객체. 원하는 스타일의 스타일을 맞춤설정하려면 이 패턴을 따르세요. 위의 마커 맞춤설정 매개변수 중 하나를 사용하여 마커를 제출할 수 있습니다.

자바스크립트

vehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

맞춤설정 함수를 사용하여 마커의 스타일 지정 변경

다음 예는 차량 마커의 스타일을 구성하는 방법을 보여줍니다. 팔로우 이 패턴을 사용하여 마커의 스타일을 원하는 대로 지정할 수 있습니다. 맞춤 매개변수를 설정할 수 있습니다.

자바스크립트

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

마커에 클릭 처리 추가

다음 예는 차량 마커에 클릭 처리를 추가하는 방법을 보여줍니다. 이 패턴을 따라 원하는 마커를 사용하여 마커에 클릭 처리를 추가하세요. 맞춤 매개변수를 설정할 수 있습니다.

자바스크립트

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

TypeScript

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

표시되는 마커 필터링

다음 예는 표시할 차량 마커를 필터링하는 방법을 보여줍니다. 마커 맞춤설정을 사용하여 마커를 필터링하려면 이 패턴을 따르세요. 매개변수를 포함해야 합니다.

자바스크립트

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
      if (remainingWaypoints > 10) {
        params.marker.setVisible(false);
      }
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
    if (remainingWaypoints > 10) {
      params.marker.setVisible(false);
    }
  };

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

Fleet 추적 라이브러리를 사용하면 따라가는 차량의 경로를 지도에 표시합니다. 라이브러리는 google.maps.Polyline 차량의 활성 또는 남은 상태에 있는 각 좌표 쌍의 객체입니다. 경로를 통해 지정할 수 있습니다. 다중선 맞춤설정을 지정하여 Polyline 객체의 스타일을 지정할 수 있습니다. 이 라이브러리는 두 가지 상황에서 이러한 맞춤설정을 적용합니다. 객체에 사용되는 데이터가 변경된 경우 객체를 지도에 추가할 수 있습니다.

마커 맞춤설정과 마찬가지로 PolylineOptions 일치하는 모든 Polyline 객체에 적용됩니다. 볼 수 있습니다.

마찬가지로 맞춤설정 기능을 지정할 수 있습니다. 맞춤설정 함수 Fleet Engine에서 전송한 데이터를 기반으로 객체의 개별 스타일을 지정할 수 있습니다. 이 함수는 객체의 현재 상태에 따라 각 객체의 스타일을 차량 예를 들어 Polyline 객체에 더 깊은 명암으로 색상을 지정합니다. 차량이 느리게 움직일 때 두꺼워집니다. 또한 이를 기반으로 Polyline 객체의 스타일을 지정합니다. 확인할 수 있습니다

여기에서 제공된 매개변수를 사용하여 맞춤설정을 지정할 수 있습니다. FleetEngineVehicleLocationProviderOptions 차량의 다양한 경로 상태에 대한 맞춤설정을 설정할 수 있습니다. 이미 여행했는지, 적극적으로 여행했는지, 또는 아직 여행하지 않았는지를 나타내는 측정항목입니다. 이 매개변수는 다음과 같습니다.

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

다음 예는 Polyline 객체의 스타일 지정을 구성하는 방법을 보여줍니다. 다음 코드로 교체합니다. PolylineOptions 다음 중 하나를 사용하여 Polyline 객체의 스타일을 맞춤설정하려면 다음 패턴을 따르세요. 설정하겠습니다.

자바스크립트

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

TypeScript

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

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

다음 예시에서는 활성 Polyline 객체의 제공합니다. Polyline 객체의 스타일을 맞춤설정하려면 다음 패턴을 따르세요. 을 클릭합니다.

자바스크립트

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params) => {
    const distance = params.vehicle.waypoints[0].distanceMeters;
    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: VehiclePolylineCustomizationFunctionParams) => {
    const distance = params.vehicle.waypoints[0].distanceMeters;
    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 속성:

자바스크립트

remainingPolylineCustomization = {visible: false};

TypeScript

remainingPolylineCustomization = {visible: false};

트래픽 인식 Polyline 객체 렌더링

Fleet Engine이 활성 및 나머지 경로의 트래픽 속도 데이터를 반환합니다. 따라갑니다. 이 정보를 사용하여 Polyline의 스타일을 지정할 수 있습니다. 객체를 조정할 수 있습니다.

자바스크립트

// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
  FleetEngineVehicleLocationProvider.
      TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;

// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
  (params) => {
    FleetEngineVehicleLocationProvider.
        TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
    for (const polylineObject of params.polylines) {
      if (polylineObject.get('strokeColor') === '#05f') {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

TypeScript

// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
  FleetEngineVehicleLocationProvider.
      TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;

// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
  (params: VehiclePolylineCustomizationFunctionParams) => {
    FleetEngineVehicleLocationProvider.
        TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
    for (const polylineObject of params.polylines) {
      if (polylineObject.get('strokeColor') === '#05f') {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

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

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

다음 예는 InfoWindow를 만들어 차량 마커

자바스크립트

// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
    {disableAutoPan: true});

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

    // 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 vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineVehicleLocationProviderUpdateEvent) => {
  if (e.vehicle) {
    const distance =
          e.vehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next drop-off.`);
    // 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();

자동 맞추기 사용 중지

지도가 표시 영역을 차량에 자동으로 맞추지 않고 예상 경로를 따라가게 할 수 있습니다. 다음 예는 여정 공유 지도를 구성할 때 자동 적합을 사용 중지하는 방법 합니다.

자바스크립트

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 Oracle Park Stadium
        var oraclePark = { lat: 37.780087547237365, lng: -122.38948437884427 };,
        // 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 Oracle Park
        var marker = new google.maps.Marker({ position: oraclePark, 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 Journey 공유 라이브러리를 추가하려면 다음 안내를 따르세요.

  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 FleetEngineVehicleLocationProvider
        // as appropriate.
        locationProvider = new google.maps.journeySharing.FleetEngineVehicleLocationProvider({
          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.vehicleId = VEHICLE_ID;

          // (4) Add customizations like before.

          // The location of Oracle Park
          var oraclePark = {lat: 37.77995187146094, lng: -122.38957020952795};
          // 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 Oracle Park
          var marker = new google.maps.Marker({position: oraclePark, 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&v=beta"
    ></script>
  </body>
</html>

Oracle Park 근처에서 지정된 ID로 차량을 운행하면 있습니다.