این صفحه نمونههایی از نحوه استفاده از کتابخانههای کلاینت Navigation Connect برای فراخوانی متدهای زیر را ارائه میدهد:
کتابخانههای کلاینت را نصب کنید
برای دستورالعملهای نصب، به کتابخانههای کلاینت Navigation Connect مراجعه کنید.
احراز هویت
وقتی از کتابخانههای کلاینت استفاده میکنید، از اعتبارنامههای پیشفرض برنامه (ADC) برای احراز هویت استفاده میکنید. برای اطلاعات بیشتر در مورد راهاندازی ADC، به «ارائه اعتبارنامه برای اعتبارنامههای پیشفرض برنامه » مراجعه کنید. برای اطلاعات بیشتر در مورد استفاده از ADC با کتابخانههای کلاینت، به «احراز هویت با استفاده از کتابخانههای کلاینت» مراجعه کنید.
مثالهای این صفحه از اعتبارنامههای پیشفرض برنامه استفاده میکنند.
مثالها
ایجاد یک سفر ( CreateTrip )
مثالهای زیر نحوه فراخوانی CreateTrip برای مقداردهی اولیه یک سفر و دریافت توکن سفر احراز هویت شده را نشان میدهند.
پایتون
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}")
نود جی اس
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}`); } }
جاوا
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 برای بازیابی وضعیت لحظهای، تلهمتری و دادههای مسیر باقیمانده برای یک سفر نشان میدهند.
پایتون
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}")
نود جی اس
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}`); } }
جاوا
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}"); } } }