이 페이지에서는 Navigation Connect 클라이언트 라이브러리를 사용하여 다음 메서드를 호출하는 방법을 보여주는 예를 제공합니다.
클라이언트 라이브러리 설치
설치 안내는 Navigation Connect 클라이언트 라이브러리를 참조하세요.
인증
클라이언트 라이브러리를 사용할 때는 애플리케이션 기본 사용자 인증 정보 (ADC) 를 사용하여 인증합니다. ADC 설정은 애플리케이션 기본 사용자 인증 정보에 대한 사용자 인증 정보 제공을 참조하세요. 클라이언트 라이브러리에서 ADC를 사용하는 방법은 클라이언트 라이브러리를 사용하여 인증을 참조하세요.
이 페이지의 예에서는 애플리케이션 기본 사용자 인증 정보를 사용합니다.
예
이동 만들기 (CreateTrip)
다음 예에서는 CreateTrip을 호출하여 이동을 초기화하고 인증된 이동 토큰을 가져오는 방법을 보여줍니다.
Python
from google.maps import navconnect_v1 def create_trip(project_id: str, trip_id: str, android_app_id: str, ios_app_id: str): # Initialize the client with ADC client = navconnect_v1.NavConnectServiceClient() # Construct the trip request request = navconnect_v1.CreateTripRequest( parent=f"projects/{project_id}", trip_id=trip_id, trip=navconnect_v1.Trip( android_app_id=android_app_id, ios_app_id=ios_app_id, config=navconnect_v1.TripConfig( enable_pubsub=True, ), ), ) try: response = client.create_trip(request=request) print(f"Trip Name: {response.name}") print(f"Trip State: {response.state}") print(f"Trip Token: {response.auth_token.token}") print(f"Token Expiry: {response.auth_token.expire_time}") except Exception as e: print(f"Error creating trip: {e}")
Node.js
const {NavConnectServiceClient} = require('@google-cloud/navconnect'); async function createTrip(projectId, tripId, androidAppId, iosAppId) { // Initialize the client with ADC const client = new NavConnectServiceClient(); const request = { parent: `projects/${projectId}`, tripId: tripId, trip: { androidAppId: androidAppId, iosAppId: iosAppId, config: { enablePubsub: true, }, }, }; try { const [response] = await client.createTrip(request); console.log(`Trip Name: ${response.name}`); console.log(`Trip State: ${response.state}`); console.log(`Trip Token: ${response.authToken.token}`); console.log(`Token Expiry: ${response.authToken.expireTime}`); } catch (error) { console.error(`Error creating trip: ${error}`); } }
Java
import com.google.maps.navconnect.v1.CreateTripRequest; import com.google.maps.navconnect.v1.NavConnectServiceClient; import com.google.maps.navconnect.v1.Trip; import com.google.maps.navconnect.v1.TripConfig; public class CreateTripExample { public static void createTrip( String projectId, String tripId, String androidAppId, String iosAppId) throws Exception { // Initialize the client with ADC try (NavConnectServiceClient client = NavConnectServiceClient.create()) { CreateTripRequest request = CreateTripRequest.newBuilder() .setParent("projects/" + projectId) .setTripId(tripId) .setTrip( Trip.newBuilder() .setAndroidAppId(androidAppId) .setIosAppId(iosAppId) .setConfig(TripConfig.newBuilder().setEnablePubsub(true).build()) .build()) .build(); Trip response = client.createTrip(request); System.out.println("Trip Name: " + response.getName()); System.out.println("Trip State: " + response.getState()); System.out.println("Trip Token: " + response.getAuthToken().getToken()); } } }
Go
package main import ( "context" "fmt" "log" navconnect "cloud.google.com/go/maps/navconnect/apiv1" navconnectpb "cloud.google.com/go/maps/navconnect/apiv1/navconnectpb" ) func createTrip(ctx context.Context, projectID, tripID, androidAppID, iosAppID string) { // Initialize the client with ADC client, err := navconnect.NewNavConnectClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() req := &navconnectpb.CreateTripRequest{ Parent: fmt.Sprintf("projects/%s", projectID), TripId: tripID, Trip: &navconnectpb.Trip{ AndroidAppId: androidAppID, IosAppId: iosAppID, Config: &navconnectpb.TripConfig{ EnablePubsub: true, }, }, } resp, err := client.CreateTrip(ctx, req) if err != nil { log.Fatalf("Failed to create trip: %v", err) } fmt.Printf("Trip Name: %s\n", resp.GetName()) fmt.Printf("Trip State: %s\n", resp.GetState()) fmt.Printf("Trip Token: %s\n", resp.GetAuthToken().GetToken()) }
.NET
using Google.Maps.NavConnect.V1; using System; using System.Threading.Tasks; public class NavConnectSamples { public static async Task CreateTripAsync(string projectId, string tripId, string androidAppId, string iosAppId) { // Initialize the client with ADC NavConnectServiceClient client = await NavConnectServiceClient.CreateAsync(); CreateTripRequest request = new CreateTripRequest { Parent = $"projects/{projectId}", TripId = tripId, Trip = new Trip { AndroidAppId = androidAppId, IosAppId = iosAppId, Config = new TripConfig { EnablePubsub = true } } }; try { Trip response = await client.CreateTripAsync(request); Console.WriteLine($"Trip Name: {response.Name}"); Console.WriteLine($"Trip State: {response.State}"); Console.WriteLine($"Trip Token: {response.AuthToken.Token}"); } catch (Exception ex) { Console.WriteLine($"Error creating trip: {ex.Message}"); } } }
이동 데이터 검색 (GetTrip)
다음 예에서는 GetTrip을 호출하여 이동의 실시간 상태, 원격 분석, 남은 경로 데이터를 검색하는 방법을 보여줍니다.
Python
from google.maps import navconnect_v1 def get_trip(project_id: str, trip_id: str): # Initialize the client with ADC client = navconnect_v1.NavConnectServiceClient() request = navconnect_v1.GetTripRequest( name=f"projects/{project_id}/trips/{trip_id}", route_polyline_format=navconnect_v1.GetTripRequest.RoutePolylineFormat.GEO_JSON, ) try: response = client.get_trip(request=request) print(f"Trip Status: {response.state}") if response.execution: print(f"Remaining Duration: {response.execution.remaining_duration}") print(f"Remaining Distance (m): {response.execution.remaining_distance_meters}") except Exception as e: print(f"Error retrieving trip: {e}")
Node.js
const {NavConnectServiceClient} = require('@google-cloud/navconnect'); async function getTrip(projectId, tripId) { // Initialize the client with ADC const client = new NavConnectServiceClient(); const request = { name: `projects/${projectId}/trips/${tripId}`, routePolylineFormat: 'GEO_JSON', }; try { const [response] = await client.getTrip(request); console.log(`Trip Status: ${response.state}`); if (response.execution) { console.log(`Remaining Duration: ${response.execution.remainingDuration}`); console.log(`Remaining Distance (m): ${response.execution.remainingDistanceMeters}`); } } catch (error) { console.error(`Error retrieving trip: ${error}`); } }
Java
import com.google.maps.navconnect.v1.GetTripRequest; import com.google.maps.navconnect.v1.NavConnectServiceClient; import com.google.maps.navconnect.v1.Trip; public class GetTripExample { public static void getTrip(String projectId, String tripId) throws Exception { // Initialize the client with ADC try (NavConnectServiceClient client = NavConnectServiceClient.create()) { GetTripRequest request = GetTripRequest.newBuilder() .setName("projects/" + projectId + "/trips/" + tripId) .setRoutePolylineFormat(GetTripRequest.RoutePolylineFormat.GEO_JSON) .build(); Trip response = client.getTrip(request); System.out.println("Trip Status: " + response.getState()); if (response.hasExecution()) { System.out.println( "Remaining Distance (m): " + response.getExecution().getRemainingDistanceMeters()); } } } }
Go
package main import ( "context" "fmt" "log" navconnect "cloud.google.com/go/maps/navconnect/apiv1" navconnectpb "cloud.google.com/go/maps/navconnect/apiv1/navconnectpb" ) func getTrip(ctx context.Context, projectID, tripID string) { // Initialize the client with ADC client, err := navconnect.NewNavConnectClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() req := &navconnectpb.GetTripRequest{ Name: fmt.Sprintf("projects/%s/trips/%s", projectID, tripID), RoutePolylineFormat: navconnectpb.GetTripRequest_GEO_JSON, } resp, err := client.GetTrip(ctx, req) if err != nil { log.Fatalf("Failed to get trip: %v", err) } fmt.Printf("Trip Status: %s\n", resp.GetState()) if exec := resp.GetExecution(); exec != nil { fmt.Printf("Remaining Distance (m): %d\n", exec.GetRemainingDistanceMeters()) } }
.NET
using Google.Maps.NavConnect.V1; using System; using System.Threading.Tasks; public class NavConnectGetSample { public static async Task GetTripAsync(string projectId, string tripId) { // Initialize the client with ADC NavConnectServiceClient client = await NavConnectServiceClient.CreateAsync(); GetTripRequest request = new GetTripRequest { Name = $"projects/{projectId}/trips/{tripId}", RoutePolylineFormat = GetTripRequest.Types.RoutePolylineFormat.GeoJson }; try { Trip response = await client.GetTripAsync(request); Console.WriteLine($"Trip Status: {response.State}"); if (response.Execution != null) { Console.WriteLine($"Remaining Distance (m): {response.Execution.RemainingDistanceMeters}"); } } catch (Exception ex) { Console.WriteLine($"Error retrieving trip: {ex.Message}"); } } }