Calcular uma matriz de rota
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
É possível calcular a distância e a duração de um trajeto para várias origens e destinos usando o método ComputeRouteMatrix
da API Routes Preferred. O ComputeRouteMatrix
é compatível com
chamadas gRPC de streaming e chamadas HTTP REST.
Com uma lista de pares de origem e destino, ComputeRouteMatrix
calcula a distância e a duração de um trajeto que começa em cada origem e termina em cada destino. Cada elemento do stream corresponde
às informações de uma única rota.
O método ComputeRouteMatrix
tem várias vantagens em relação ao serviço de matriz de distâncias:
- O streaming permite que os elementos sejam retornados antes que toda a matriz seja calculada, reduzindo a latência.
ComputeRouteMatrix
tem opções refinadas para o cálculo de tráfego, permitindo que você tome decisões de compensação entre qualidade e latência.
- As solicitações são executadas com uma prioridade mais alta na infraestrutura do Google, o que resulta em maior disponibilidade.
- É possível especificar o sentido (direção do trajeto) e informações sobre o lado da via para os pontos de referência.
- É possível solicitar que as informações de pedágio sejam retornadas, junto com a distância da rota e o HEC.
Ativar o método ComputeRouteMatrix
Antes de usar o método ComputeRouteMatrix
no código, é necessário ativá-lo. Para mais informações sobre como ativar os métodos da API Routes Preferred, consulte Primeiros passos.
Usar o método ComputeRouteMatrix
O método ComputeRouteMatrix
está disponível pelo endpoint Routes Preferred
v1.
Consulte a seguinte documentação para mais informações:
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
As etapas genéricas a seguir descrevem como usar o gRPC para chamar
o método ComputeRouteMatrix
:
Confira os protobuffers necessários no repositório googleapis:
https://github.com/googleapis/googleapis/tree/master/google/maps/routes
Alguns sistemas de build, como o Go, podem fazer isso automaticamente.
Usando sua linguagem e conjunto de ferramentas de build preferidos, gere o código
protobuffer relevante.
Gere sua solicitação. Dois metadados obrigatórios precisam ser enviados
com a solicitação:
- X-Goog-Api-Key precisa ser definido como sua chave de API.
X-Goog-Fieldmask precisa ser definido como uma lista separada por vírgulas dos campos
que você quer na resposta. Por exemplo, X-Goog-FieldMask: originIndex,destinationIndex,duration,distanceMeters,status.
Você pode usar o caractere curinga (*) para indicar todos os campos, mas isso não é recomendado. Use o caractere curinga para testar e entender a resposta da API, mas liste explicitamente os campos que você quer na máscara de campo no seu código de produção.
Para mais informações sobre como criar a string de máscara de campo, consulte
https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto.
Desativar campos desnecessários pode reduzir a latência, já que eles podem exigir mais computação. Sua latência vai permanecer
estável se você especificar os campos necessários e novos campos que exigem
mais computação forem adicionados depois.
Envie sua solicitação para routespreferred.googleapis.com:443
.Use o protocolo TLS.
Para exemplos de uso do método ComputeRouteMatrix
, consulte
Exemplos de como calcular uma matriz de rotas (Beta).
Uma característica distintiva do método ComputeRouteMatrix
é que
códigos de erro podem ser retornados para todo o fluxo ou para elementos
individuais. Por exemplo, a conexão de stream retorna um erro se a solicitação
estiver malformada (por exemplo, se tiver zero origens). No entanto, se um erro se aplicar
a apenas alguns elementos do fluxo (por exemplo, definir um ID de lugar inválido
para uma origem), somente os elementos afetados pelo erro vão conter códigos de erro.
Não há garantia de que os elementos retornados pelo stream serão retornados em alguma ordem. Por isso, cada elemento contém um origin_index
e um destination_index
. Para as origens e destinos especificados
pela solicitação, a origem da rota é equivalente a origins[origin_index]
para um determinado elemento, e o destino da rota é equivalente
a destinations[destination_index]
. Esses arrays são indexados com zero. É importante armazenar as ordens das listas de origem e destino.
Cálculo de pedágios
Para saber como calcular as taxas de pedágio, consulte
Calcular taxas de pedágio.
Para exemplos de cálculo de pedágios, consulte
Exemplos de cálculo de uma matriz de rotas.
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-09-10 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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)."]]