На этой странице приведены примеры использования клиентских библиотек 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()); } } }
Идти
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()) }
.СЕТЬ
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()); } } } }
Идти
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()) } }
.СЕТЬ
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}"); } } }