Auf dieser Seite finden Sie Beispiele für die Verwendung der Navigation Connect-Clientbibliotheken zum Aufrufen der folgenden Methoden:
Clientbibliotheken installieren
Eine Installationsanleitung finden Sie unter Navigation Connect-Clientbibliotheken.
Authentifizierung
Wenn Sie Clientbibliotheken verwenden, authentifizieren Sie sich mit Standardanmeldedaten für Anwendungen (Application Default Credentials, ADC). Informationen zum Einrichten von ADC finden Sie unter Anmeldedaten für Standardanmeldedaten für Anwendungen bereitstellen. Informationen zur Verwendung von ADC mit Clientbibliotheken finden Sie unter Mit Clientbibliotheken authentifizieren.
In den Beispielen auf dieser Seite werden Standardanmeldedaten für Anwendungen verwendet.
Beispiele
Fahrt erstellen (CreateTrip)
In den folgenden Beispielen wird gezeigt, wie Sie CreateTrip aufrufen, um eine Fahrt zu initialisieren und ein authentifiziertes Fahrt-Token zu erhalten.
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}"); } } }
Fahrtdaten abrufen (GetTrip)
In den folgenden Beispielen wird gezeigt, wie Sie GetTrip aufrufen, um den Echtzeitstatus, die Telemetrie und die verbleibenden Routendaten für eine Fahrt abzurufen.
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}"); } } }