자바스크립트용 소비자 SDK 시작하기

JavaScript SDK를 사용하면 이미지, 오디오, 동영상, Fleet Engine에서 추적된 차량 및 관심 위치를 보여줍니다. 도서관 삽입형 대체 자바스크립트 지도 구성요소가 포함되어 있습니다. 연결할 표준 google.maps.Map 항목 및 데이터 구성요소 사용할 수 있습니다 JavaScript SDK를 사용하면 웹 애플리케이션에서 맞춤설정이 가능한 애니메이션 이동 및 주문 진행 환경을 제공할 수 있습니다.

구성요소

시각화를 위한 구성요소를 제공하는 JavaScript SDK 운전자의 도착예정시간에 대한 원시 데이터 피드와 함께 또는 남은 거리를 확인할 수 있습니다.

이동 및 주문 진행 상황 지도뷰

지도뷰 구성요소는 차량 및 경유지의 위치를 시각화합니다. 차량의 경로를 알고 있는 경우 지도뷰 구성요소가 애니메이션됩니다. 자동으로 학습됩니다.

이동 위치 정보 제공자

JavaScript SDK에 여행 위치가 포함되어 있음 추적된 객체의 위치 정보를 피드하는 이동 및 주문 진행 상황 맵

이동 위치 정보 제공자를 사용하여 다음을 추적할 수 있습니다.

  • 여정의 승차 또는 하차 위치입니다.
  • 이동에 할당된 차량의 위치와 경로입니다.

추적된 위치 객체

위치 정보 제공자는 경유지 및 차량과 같은 객체의 위치를 추적합니다.

출발지 위치

출발지 위치는 여정이 시작되는 위치입니다. 그것은 표시 승차 위치입니다.

대상 위치

목적지 위치는 여정이 끝나는 위치입니다. 하차 위치를 표시합니다.

경유지 위치

경유지 위치는 추적한 여정에 있는 임의의 위치입니다. 예를 들어, 버스 노선의 각 정류장은 경유지 위치입니다.

차량 위치

차량 위치는 차량이 추적된 위치입니다. 필요한 경우 차량의 경로를 포함합니다.

인증 토큰 가져오기 도구

Fleet Engine에 저장된 위치 데이터에 대한 액세스를 제어하려면 다음을 수행해야 합니다. Fleet Engine용 JSON 웹 토큰 (JWT) 발급 서비스 구현 있습니다. 그런 다음 인증 토큰 가져오기 프로그램을 SDK를 사용하여 웹 애플리케이션의 위치 데이터 액세스를 인증해야 합니다.

스타일 지정 옵션

마커와 폴리라인 스타일은 추적된 위치 객체를 기반으로 합니다. 이때 기본 스타일을 스타일에 맞게 변경할 수 있는 맞춤 스타일 지정 옵션 웹 애플리케이션의 API입니다

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

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

차량

차량 공유 차량은 이동에 할당된 시점부터 표시됩니다. 전달될 수 있습니다 이동이 취소되면 차량이 더 오래 표시됩니다.

기타 모든 위치 마커

출발지, 목적지 및 경유지에 대한 다른 모든 위치 마커는 항상 지도에 표시됩니다. 예: 차량 공유 하차 위치 배송 위치와 관계없이 항상 지도에 상태를 파악할 수 있습니다.

JavaScript SDK 시작하기

JavaScript SDK를 사용하기 전에 다음 사항을 확인하세요. Fleet Engine에 익숙함 API 키 가져오기를 통해 API 키를 가져올 수도 있습니다

차량 공유 여행을 추적하려면 먼저 이동 ID 소유권 주장을 만드세요.

이동 ID 소유권 주장 만들기

이동 위치 정보 제공자를 사용하여 이동을 추적하려면 여행 ID 클레임으로 JSON 웹 토큰 (JWT)을 만듭니다.

JWT 페이로드를 만들려면 승인 섹션에 클레임을 추가합니다. 값을 tripid로 설정하고 해당 값을 이동 ID로 설정합니다.

다음 예시에서는 여행 ID로 추적하기 위한 토큰을 만드는 방법을 보여줍니다.

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "private_key_id_of_consumer_service_account"
}
.
{
  "iss": "consumer@yourgcpproject.iam.gserviceaccount.com",
  "sub": "consumer@yourgcpproject.iam.gserviceaccount.com",
  "aud": "https://fleetengine.googleapis.com/",
  "iat": 1511900000,
  "exp": 1511903600,
  "scope": "https://www.googleapis.com/auth/xapi",
  "authorization": {
     "tripid": "tid_12345",
   }
}

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

인증 토큰 가져오기 프로그램을 만들어 발급된 토큰을 가져올 수 있습니다. 적절한 클레임으로 바꿉니다. 계정 인증서가 생성됩니다 토큰만 발급하는 것이 중요함 인증서를 다른 클라이언트와 공유할 수 없습니다. 그렇지 않으면 시스템의 보안이 침해됩니다.

가져오기 프로그램은 데이터 구조를 반환해야 합니다. 두 개의 필드로 구성되며 프로미스로 래핑됩니다.

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

JavaScript 소비자 SDK는 인증 토큰을 통해 토큰을 요청합니다. 가져오기를 실행할 수 있습니다.

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

그렇지 않으면 SDK가 이전에 발행된 여전히 유효한 토큰을 사용하며 가져올 수 있습니다

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

자바스크립트

async 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.jwt,
    expiresInSeconds: data.expirationTimestamp - Date.now(),
  };
}

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

  • 엔드포인트는 토큰의 만료 시간을 반환해야 합니다. 예시 위의 경우 data.ExpiresInSeconds로 제공됩니다.
  • 인증 토큰 가져오기 프로그램은 만료 시간 (초, 를 라이브러리로 가져올 수 있습니다.
  • SERVER_TOKEN_URL은 제공자 구현에 따라 달라지며 예제 제공자의 URL은 다음과 같습니다. <ph type="x-smartling-placeholder">
      </ph>
    • https://SERVER_URL/token/driver/VEHICLEID
    • https://SERVER_URL/token/consumer/TRIPID

HTML에서 지도 로드

다음 예는 JavaScript SDK를 로드하는 방법을 보여줍니다. 가져올 수 있습니다. 콜백 매개변수는 initMap를 실행합니다. 함수를 호출합니다. defer 속성을 사용하면 브라우저에서 API가 로드되는 동안 페이지의 나머지 부분을 계속 렌더링합니다.

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

여행 후

이 섹션에서는 JavaScript SDK를 사용하는 방법을 보여줍니다. 차량 공유 또는 배달 경로를 팔로우할 수도 있습니다. 반드시 스크립트 태그에 지정된 콜백 함수에서 라이브러리 로드 코드를 실행해 보겠습니다

이동 위치 정보 제공자 인스턴스화

JavaScript SDK가 위치 정보 제공자를 미리 정의합니다. 사용할 수 있습니다 프로젝트 ID 및 인스턴스화하기 위해 토큰 팩토리에 대한 참조를 제공합니다.

자바스크립트

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

TypeScript

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

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

지도뷰 초기화

JavaScript SDK를 로드한 후 초기화 HTML 페이지에 추가합니다. 페이지에는 지도뷰를 포함하는 &lt;div&gt; 요소. &lt;div&gt; 요소 아래 예에서 이름이 map_canvas입니다.

경합 상태를 방지하려면 위치 정보 제공자의 이동 ID를 설정하세요. 을 반환합니다.

자바스크립트

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerCustomization: vehicleMarkerCustomization,
  activePolylineCustomization: activePolylineCustomization,
  // Any undefined styling options will use defaults.
});

// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.tripId = 'your-trip-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({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerCustomization: vehicleMarkerCustomization,
  activePolylineCustomization: activePolylineCustomization,
  // Any undefined styling options will use defaults.
});

// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
locationProvider.tripId = 'your-trip-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({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

변경 이벤트 수신 대기

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

자바스크립트

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

TypeScript

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

오류 처리

경로 정보 요청 트리거에서 비동기식으로 발생하는 오류 오류 이벤트입니다. 다음 예는 이러한 이벤트를 수신 대기하는 방법을 보여줍니다. 몇 가지 기본 규칙이 있습니다

자바스크립트

locationProvider.addListener('error', e => {
  // e.error contains the error that triggered the 
  // event
  console.error(e.error);
});

TypeScript

locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error contains the error that triggered the 
  // event
  console.error(e.error);
});

참고: 라이브러리 호출을 try...catch 블록으로 래핑해야 합니다. 예기치 않은 오류를 처리합니다

추적 중지

위치 정보 제공자가 경로를 추적하지 못하게 하려면 다음에서 이동 ID를 삭제하세요. 위치 정보 제공자

자바스크립트

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

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

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

자바스크립트

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

지도 구성요소의 디자인을 맞춤설정하려면 지도 스타일 지정 코드에서 직접 옵션을 설정하는 방식으로 머신러닝 모델을 빌드할 수 있습니다

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

클라우드 기반 지도 스타일 지정 를 사용하면 Google 지도를 사용하는 모든 앱에서 지도 스타일을 만들고 수정할 수 있습니다. Google Cloud 콘솔에서 새 쿼리를 실행할 수 있습니다. 지도 스타일은 Cloud 프로젝트에 지도 ID로 저장됩니다. 받는사람 JavaScript SDK 지도에 스타일을 적용하려면 mapId 및 기타 모든 mapOptions JourneySharingMapView mapId 필드는 변경할 수 없습니다. 또는 JourneySharingMapView가 인스턴스화된 후에 추가됩니다. 다음 예제는 지도 ID입니다.

자바스크립트

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

TypeScript

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

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

지도 스타일을 맞춤설정하는 또 다른 방법은 다음 작업을 할 때 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 SDK를 사용하면 있습니다. 이는 마커 맞춤설정을 지정하여 수행할 수 있는데, JavaScript SDK는 지도에 마커를 추가하기 전에, 그리고 모든 마커가 마커가 업데이트되었습니다.

가장 간단한 맞춤설정은 MarkerOptions 객체를 정의합니다. 변경사항 각 마커가 생성된 후에 객체에 지정된 값이 적용됩니다. 모든 기본 옵션을 덮어씁니다.

고급 옵션은 맞춤설정 기능을 지정하는 것입니다. 맞춤설정 함수를 사용하면 데이터를 기반으로 마커의 스타일을 지정하고 상호작용 기능을 사용할 수 있습니다. 구체적으로 이동 및 주문 Progress는 실행 중인 객체 유형에 대한 데이터를 맞춤설정 함수에 마커는 차량, 출발지, 경유지 또는 목적지를 나타냅니다. 이렇게 하면 마커 요소의 현재 상태에 따라 변경할 마커 스타일 지정 자체 예: 차량이 끝날 때까지 남은 경유지 수 정보를 얻을 수 있습니다. Fleet Engine 외부 소스의 데이터와도 조인할 수 있으며 해당 정보를 기반으로 마커의 스타일을 지정합니다.

JavaScript SDK는 FleetEngineTripLocationProviderOptions에서 다음과 같은 맞춤설정 매개변수를 제공합니다.

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

다음 예는 다음을 사용하여 차량 마커의 스타일을 구성하는 방법을 보여줍니다. MarkerOptions 객체 원하는 스타일의 스타일을 맞춤설정하려면 이 패턴을 따르세요. 이전에 설명한 마커 맞춤설정 중 하나를 사용하여 마커를 수정할 수 있습니다.

자바스크립트

vehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

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

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

자바스크립트

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

TypeScript

vehicleMarkerCustomization =
  (params: TripMarkerCustomizationFunctionParams) => {
    const distance = params.trip.remainingWaypoints.length;
    params.marker.setLabel(`${distance}`);
};

마커에 클릭 처리 추가

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

자바스크립트

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

TypeScript

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

다중선 맞춤설정 사용

JavaScript SDK를 사용하면 여행의 디자인과 분위기를 맞춤설정할 수도 있습니다. 경로를 찾을 수 있습니다. 라이브러리는 google.maps.Polyline 차량의 활성 또는 남은 상태에 있는 각 좌표 쌍의 객체입니다. 경로 를 참조하세요. 다중선 맞춤설정을 지정하여 Polyline 객체의 스타일을 지정할 수 있습니다. 이 라이브러리는 두 가지 상황에서 이러한 맞춤설정을 적용합니다. 객체에 사용되는 데이터가 변경된 경우 객체를 지도에 추가할 수 있습니다.

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

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

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

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.trip.remainingWaypoints[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: TripPolylineCustomizationFunctionParams) => {
    const distance = params.trip.remainingWaypoints[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 =
  FleetEngineTripLocationProvider.
      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) => {
    FleetEngineTripLocationProvider.
        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 =
  FleetEngineTripLocationProvider.
      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: TripPolylineCustomizationFunctionParams) => {
    FleetEngineTripLocationProvider.
        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});

locationProvider.addListener('update', e => {
  const stopsCount = e.trip.remainingWaypoints.length;
  infoWindow.setContent(
      `Your vehicle is ${stopsCount} stops away.`);

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

locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
  const stopsCount = e.trip.remainingWaypoints.length;
  infoWindow.setContent(
      `Your vehicle is ${stopsCount} stops away.`);

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

기존 지도 바꾸기

JavaScript SDK를 사용하여 마커 또는 기타 맞춤설정이 포함된 기존 지도 계속 사용할 수 있습니다.

예를 들어 표준 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, centered at Uluru
  var map = new google.maps.Map(document.getElementById('map'));
  map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

  // The marker, 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>

JavaScript SDK를 추가하는 방법은 다음과 같습니다.

  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
async 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.
  locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
    projectId: "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
  });

  locationProvider.tripId = TRIP_ID;

    // (4) Add customizations like before.

    // The location of Uluru
    var uluru = {lat: -25.344, lng: 131.036};
    // The map, centered at Uluru
    var map = mapView.map;
    map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
    // The marker, 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 SDK to the API loader.
    -->
    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
    </script>
  </body>
</html>

승차할 수 있는 적의 항공기와 함께 지정한 ID가 있으면 지도에 렌더링됩니다.