Calcola una matrice di route
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Puoi calcolare la distanza e la durata di un percorso per più origini e destinazioni utilizzando il metodo ComputeRouteMatrix
dell'API Routes Preferred. ComputeRouteMatrix
supporta
sia le chiamate gRPC di streaming sia le chiamate HTTP REST.
Dato un elenco di coppie di origine e destinazione, ComputeRouteMatrix
calcola la distanza e la durata di un percorso che inizia da ogni origine
e termina in ogni destinazione. Ogni elemento dello stream corrisponde
alle informazioni per un singolo itinerario.
Il metodo ComputeRouteMatrix
presenta diversi vantaggi rispetto al servizio Distance Matrix:
- Lo streaming consente di restituire gli elementi prima che l'intera matrice
sia stata calcolata, riducendo la latenza.
ComputeRouteMatrix
offre opzioni granulari per il calcolo del traffico,
consentendoti di prendere decisioni sul compromesso tra qualità e latenza.
- Le richieste vengono eseguite con una priorità più elevata all'interno dell'infrastruttura di Google,
il che si traduce in una maggiore disponibilità.
- Puoi specificare le informazioni su direzione di marcia e lato della strada per i waypoint.
- Puoi richiedere la restituzione delle informazioni sui pedaggi, insieme
alla distanza del percorso e all'orario di arrivo stimato.
Abilita il metodo ComputeRouteMatrix
Prima di poter utilizzare il metodo ComputeRouteMatrix
nel tuo codice, devi
attivarlo. Per saperne di più sull'abilitazione dei metodi dell'API Routes Preferred, consulta la guida introduttiva.
Utilizzare il metodo ComputeRouteMatrix
Il metodo ComputeRouteMatrix
è disponibile tramite l'endpoint Routes Preferred
v1.
Per informazioni più dettagliate, consulta la seguente documentazione:
gRPC:
https://developers.google.com/maps/documentation/routes_preferred/reference/rpc/google.maps.routes.v1
REST:
https://developers.google.com/maps/documentation/routes_preferred/reference/rest/v1/TopLevel/computeRouteMatrix
I seguenti passaggi generici descrivono come utilizzare gRPC per chiamare il metodo ComputeRouteMatrix
:
Controlla i protobuffer necessari dal repository googleapis:
https://github.com/googleapis/googleapis/tree/master/google/maps/routes
Tieni presente che alcuni sistemi di build, come Go, potrebbero farlo automaticamente.
Utilizzando la lingua e il set di strumenti di compilazione che preferisci, genera il codice protobuffer pertinente.
Genera la richiesta. Con la richiesta devono essere inviati due metadati obbligatori:
- X-Goog-Api-Key deve essere impostato sulla tua chiave API.
X-Goog-Fieldmask deve essere impostato su un elenco di campi separati da virgole
che ti servono dalla risposta. Ad esempio,
X-Goog-FieldMask: originIndex,destinationIndex,duration,distanceMeters,status.
Puoi utilizzare il carattere jolly (*) per indicare tutti i campi, ma è
sconsigliato. Utilizza il carattere jolly per testare e comprendere la
risposta dell'API, ma elenca esplicitamente i campi che vuoi nella maschera di campo
nel codice di produzione.
Per ulteriori informazioni su come creare la stringa della maschera di campo, consulta
https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto.
Tieni presente che la disattivazione dei campi non necessari può ridurre la latenza, in quanto
questi campi potrebbero richiedere ulteriori calcoli. La latenza rimarrà
stabile se specifichi i campi di cui hai bisogno e i nuovi campi che richiedono
più calcoli vengono aggiunti in un secondo momento.
Invia la richiesta a routespreferred.googleapis.com:443
.Devi utilizzare
il protocollo TLS.
Per esempi di utilizzo del metodo ComputeRouteMatrix
, consulta
Esempi di calcolo di una matrice di itinerari (beta).
Una caratteristica distintiva del metodo ComputeRouteMatrix
è che
i codici di errore possono essere restituiti per l'intero stream o per singoli
elementi. Ad esempio, la connessione allo stream restituisce un errore se la richiesta
non è formattata correttamente (ad esempio, ha zero origini). Tuttavia, se un errore riguarda
solo alcuni elementi del flusso (ad esempio, l'impostazione di un ID luogo non valido
per un'origine), solo gli elementi interessati dall'errore contengono codici di errore.
Non è garantito che gli elementi restituiti dal flusso vengano restituiti
in un ordine specifico. Per questo motivo, ogni elemento contiene un origin_index
e un destination_index
. Per le origini e le destinazioni specificate
dalla richiesta, l'origine dell'itinerario è equivalente a origins[origin_index]
per un determinato elemento e la destinazione dell'itinerario è equivalente
a destinations[destination_index]
. Questi array sono indicizzati su base zero. È
importante memorizzare l'ordine degli elenchi di origini e destinazioni.
Calcolo dei pedaggi
Per informazioni sul calcolo dei pedaggi, consulta
Calcolare i pedaggi.
Per esempi di calcolo dei pedaggi, consulta la sezione
Esempi di calcolo di una matrice di itinerari.
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2025-09-10 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-10 UTC."],[[["\u003cp\u003eThe \u003ccode\u003eComputeRouteMatrix\u003c/code\u003e method in the Routes Preferred API calculates distances and durations for multiple origin-destination pairs, offering advantages like streaming results and traffic calculation options.\u003c/p\u003e\n"],["\u003cp\u003eIt's necessary to enable the \u003ccode\u003eComputeRouteMatrix\u003c/code\u003e method and understand quota limits before implementation, ensuring compliance with Google Maps Platform terms.\u003c/p\u003e\n"],["\u003cp\u003eThe method can be accessed through gRPC or REST, with specific steps outlined for using gRPC, including generating protobuffer code and configuring requests.\u003c/p\u003e\n"],["\u003cp\u003eResponses include \u003ccode\u003eorigin_index\u003c/code\u003e and \u003ccode\u003edestination_index\u003c/code\u003e to correlate results with input data since the order of elements is not guaranteed.\u003c/p\u003e\n"],["\u003cp\u003eToll fee calculation functionality is available within \u003ccode\u003eComputeRouteMatrix\u003c/code\u003e, allowing developers to incorporate toll costs into route planning.\u003c/p\u003e\n"]]],["The `ComputeRouteMatrix` method of the Routes Preferred API calculates route distance and duration for multiple origins and destinations via streaming gRPC or REST HTTP calls. It offers lower latency, fine-grained traffic options, higher availability, waypoint specifications, and toll information. To use it, enable the method, and send requests with API key and field mask. The method returns elements with `origin_index` and `destination_index`. Error codes can be returned for the entire stream or per individual element.\n"],null,["# Compute a Route Matrix\n\n\u003cbr /\u003e\n\n| This product or feature is in Preview (pre-GA). Pre-GA products and features might have limited support, and changes to pre-GA products and features might not be compatible with other pre-GA versions. Pre-GA Offerings are covered by the [Google\n| Maps Platform Service Specific Terms](https://cloud.google.com/maps-platform/terms/maps-service-terms). For more information, see the [launch stage\n| descriptions](/maps/launch-stages).\n\n\u003cbr /\u003e\n\nYou can calculate the distance and duration of a route for multiple\norigins and destinations by using the `ComputeRouteMatrix` method\nof the Routes Preferred API. `ComputeRouteMatrix` supports\nboth streaming gRPC calls and REST HTTP calls.\n\nGiven a list of origin and destination pairs, `ComputeRouteMatrix`\ncalculates the distance and duration of a route starting at each origin\nand ending at each destination. Each element of the stream corresponds\nto the information for a single route.\n\nThe `ComputeRouteMatrix` method has several advantages over the\nDistance Matrix Service:\n\n- Streaming allows elements to be returned before the entire matrix has been calculated, lowering latency.\n- `ComputeRouteMatrix` has fine-grained options for traffic calculation, letting you make quality-latency tradeoff decisions.\n- Requests are run at a higher priority within Google's infrastructure, which results in higher availability.\n- You can specify heading (direction of travel) and side-of-road information for waypoints.\n- You can request for toll information to be returned, along with route distance and ETA.\n\nEnable the ComputeRouteMatrix method\n------------------------------------\n\nBefore you can use the `ComputeRouteMatrix` method in your code, you must\nenable it. For more information on enabling Routes Preferred API\nmethods, see [Getting Started](/maps/documentation/routes_preferred/get_started).\n| **Important:** Check your quota limits for Routes Preferred API methods. If you need to increase your quota limits, contact support by filing a case on the [Google Maps Platform support page](https://console.cloud.google.com/google/maps-apis/support) in the Google Cloud Console, or by calling the [Google Cloud Support Hotline](/maps/documentation/routes_preferred/support#support_hotline).\n\nUse the ComputeRouteMatrix method\n---------------------------------\n\nThe `ComputeRouteMatrix` method is available through the Routes Preferred\n*v1* endpoint.\n\nSee the following documentation for more detailed information:\n\ngRPC:\n\u003chttps://developers.google.com/maps/documentation/routes_preferred/reference/rpc/google.maps.routes.v1\u003e\n\nREST:\n\u003chttps://developers.google.com/maps/documentation/routes_preferred/reference/rest/v1/TopLevel/computeRouteMatrix\u003e\n\nThe following generic steps describe how to use gRPC to call\nthe `ComputeRouteMatrix` method:\n\n1. Check out the necessary protobuffers from the googleapis repository:\n\n \u003chttps://github.com/googleapis/googleapis/tree/master/google/maps/routes\u003e\n\n Note that some build systems, such as Go, may automatically do this for you.\n2. Using your preferred language and set of build tools, generate the relevant\n protobuffer code.\n\n3. Generate your request. Two required pieces of metadata must be sent\n with the request:\n\n - *X-Goog-Api-Key* must be set to your API key.\n - *X-Goog-Fieldmask* must be set to a comma separated list of the fields\n you require from the response. For example,\n *X-Goog-FieldMask: originIndex,destinationIndex,duration,distanceMeters,status*.\n You can use the wildcard character (\\*) to denote all fields, but that is\n discouraged. Use the wildcard character to test and understand the\n API response, but explicitly list the fields you want in the field mask\n in your production code.\n\n For more information on how to construct the field mask string, see\n \u003chttps://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto\u003e.\n Note that disabling fields you do not need can reduce latency since\n those fields may require further computation. Your latency will stay\n stable if you specify the fields you need and new fields that require\n more computation are added later.\n4. Send your request to `routespreferred.googleapis.com:443`.You must use\n the TLS protocol.\n\nFor examples of using the `ComputeRouteMatrix` method, see\n[Computing a Route Matrix (Beta) Examples](/maps/documentation/routes_preferred/compute_matrix_examples).\n\nOne distinguishing feature of the `ComputeRouteMatrix` method is that\nerror codes can be returned either for the entire stream or for individual\nelements. For example, the stream connection returns an error if the request\nis malformed (for example, it has zero origins). However, if an error applies\nto just a few elements of the stream (for example, setting an invalid Place ID\nfor an origin), then only the elements affected by the error contain error codes.\n\nThe elements returned by the stream are not guaranteed to be returned\nin any order. Because of this, each element contains an `origin_index`\nand a `destination_index`. For the origins and destinations specified\nby the request, the route origin is equivalent to `origins[origin_index]`\nfor a given element and the route destination is is equivalent\nto `destinations[destination_index]`. These arrays are zero-indexed. It\nis important to store the origin and destination list orders.\n\nCalculating toll fees\n---------------------\n\nFor information on calculating toll fees, see\n[Calculate toll fees](/maps/documentation/routes_preferred/calculate_toll_fees).\n\nFor examples of calculating toll fees, see\n[Computing a Route Matrix Examples](/maps/documentation/routes_preferred/compute_matrix_examples#toll-fee-examples)."]]