diff --git a/sdk/maps/azure-maps-route/CHANGELOG.md b/sdk/maps/azure-maps-route/CHANGELOG.md new file mode 100644 index 000000000000..c420369c4c9e --- /dev/null +++ b/sdk/maps/azure-maps-route/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 1.0.0b1 (2022-10-13) + +* Initial Release diff --git a/sdk/maps/azure-maps-route/MANIFEST.in b/sdk/maps/azure-maps-route/MANIFEST.in new file mode 100644 index 000000000000..9ce0d14686b6 --- /dev/null +++ b/sdk/maps/azure-maps-route/MANIFEST.in @@ -0,0 +1,6 @@ +recursive-include tests *.py *.yaml +recursive-include samples *.py *.md +include *.md +include azure/__init__.py +include azure/maps/__init__.py +include azure/maps/route/py.typed \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/README.md b/sdk/maps/azure-maps-route/README.md new file mode 100644 index 000000000000..13a3f43beb6e --- /dev/null +++ b/sdk/maps/azure-maps-route/README.md @@ -0,0 +1,238 @@ +# Azure Maps Route Package client library for Python + +This package contains a Python SDK for Azure Maps Services for Route. +Read more about Azure Maps Services [here](https://docs.microsoft.com/azure/azure-maps/) + +[Source code](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route) | [API reference documentation](https://docs.microsoft.com/rest/api/maps/route) | [Product documentation](https://docs.microsoft.com/azure/azure-maps/) + +## _Disclaimer_ + +_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to _ + +## Getting started + +### Prerequisites + +- Python 3.6 or later is required to use this package. +- An [Azure subscription][azure_subscription] and an [Azure Maps account](https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys). +- A deployed Maps Services resource. You can create the resource via [Azure Portal][azure_portal] or [Azure CLI][azure_cli]. + +If you use Azure CLI, replace `` and `` of your choice, and select a proper [pricing tier](https://docs.microsoft.com/azure/azure-maps/choose-pricing-tier) based on your needs via the `` parameter. Please refer to [this page](https://docs.microsoft.com/cli/azure/maps/account?view=azure-cli-latest#az_maps_account_create) for more details. + +```bash +az maps account create --resource-group --account-name --sku +``` + +### Install the package + +Install the Azure Maps Service Route SDK. + +```bash +pip install azure-maps-route +``` + +### Create and Authenticate the MapsRouteClient + +To create a client object to access the Azure Maps Route API, you will need a **credential** object. Azure Maps Route client also support two ways to authenticate. + +#### 1. Authenticate with a Subscription Key Credential + +You can authenticate with your Azure Maps Subscription Key. +Once the Azure Maps Subscription Key is created, set the value of the key as environment variable: `AZURE_SUBSCRIPTION_KEY`. +Then pass an `AZURE_SUBSCRIPTION_KEY` as the `credential` parameter into an instance of [AzureKeyCredential][azure-key-credential]. + +```python +from azure.core.credentials import AzureKeyCredential +from azure.maps.route import MapsRouteClient + +credential = AzureKeyCredential(os.environ.get("AZURE_SUBSCRIPTION_KEY")) + +route_client = MapsRouteClient( + credential=credential, +) +``` + +#### 2. Authenticate with an Azure Active Directory credential + +You can authenticate with [Azure Active Directory (AAD) token credential][maps_authentication_aad] using the [Azure Identity library][azure_identity]. +Authentication by using AAD requires some initial setup: + +- Install [azure-identity][azure-key-credential] +- Register a [new AAD application][register_aad_app] +- Grant access to Azure Maps by assigning the suitable role to your service principal. Please refer to the [Manage authentication page][manage_aad_auth_page]. + +After setup, you can choose which type of [credential][azure-key-credential] from `azure.identity` to use. +As an example, [DefaultAzureCredential][default_azure_credential] +can be used to authenticate the client: + +Next, set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: +`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET` + +You will also need to specify the Azure Maps resource you intend to use by specifying the `clientId` in the client options. The Azure Maps resource client id can be found in the Authentication sections in the Azure Maps resource. Please refer to the [documentation][how_to_manage_authentication] on how to find it. + +```python +from azure.maps.route import MapsRouteClient +from azure.identity import DefaultAzureCredential + +credential = DefaultAzureCredential() +route_client = MapsRouteClient( + client_id="", + credential=credential +) +``` + +## Key concepts + +The Azure Maps Route client library for Python allows you to interact with each of the components through the use of a dedicated client object. + +### Sync Clients + +`MapsRouteClient` is the primary client for developers using the Azure Maps Route client library for Python. +Once you initialized a `MapsRouteClient` class, you can explore the methods on this client object to understand the different features of the Azure Maps Route service that you can access. + +### Async Clients + +This library includes a complete async API supported on Python 3.5+. To use it, you must first install an async transport, such as [aiohttp](https://pypi.org/project/aiohttp/). +See [azure-core documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#transport) for more information. + +Async clients and credentials should be closed when they're no longer needed. These +objects are async context managers and define async `close` methods. + +## Examples + +The following sections provide several code snippets covering some of the most common Azure Maps Route tasks, including: + +- [Request and Get Route Directions](#request-and-get-route-directions) +- [Request and Get Route Range](#reqest-and-get-route-range) +- [Get Route Matrix](#get-route-matrix) +- [Get Route Directions Batch](#get-route-directions-batch) + +### Request and Get Route Directions + +This service request returns a route between an origin and a destination, passing through waypoints if they are specified. The route will take into account factors such as current traffic and the typical road speeds on the requested day of the week and time of day. + +```python +from azure.maps.route import MapsRouteClient + +route_directions_result = client.get_route_directions(route_points=[LatLon(47.60323, -122.33028), LatLon(53.2, -106)]); +``` + +### Request and Get Route Range + +This service will calculate a set of locations that can be reached from the origin point by given coordinates and based on fuel, energy, time or distance budget that is specified. + +```python +from azure.maps.route import MapsRouteClient + +route_range_result = client.get_route_range(coordinates=LatLon(47.60323, -122.33028), time_budget_in_sec=6000); +``` + +### Get Route Matrix + +If the Matrix Route request was accepted successfully, the Location header in the response contains the URL to download the results of the request. + +Retrieves the result of a previous route matrix request. +The method returns a poller for retrieving the result. + +```python +from azure.maps.route import MapsRouteClient + +route_matrix_result = client.begin_get_route_matrix_result(matrix_id="11111111-2222-3333-4444-555555555555"); +``` + +### Get Route Directions Batch + +Retrieves the result of a previous route direction batch request. +The method returns a poller for retrieving the result. + +```python +from azure.maps.route import MapsRouteClient + +route_directions_batch_poller_result = client.begin_get_route_directions_batch_result(batch_id="11111111-2222-3333-4444-555555555555"); +``` + +## Troubleshooting + +### General + +Maps Route clients raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md). + +This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the `error_code` attribute, i.e, `exception.error_code`. + +### Logging + +This library uses the standard [logging](https://docs.python.org/3/library/logging.html) library for logging. +Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level. + +Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the `logging_enable` argument: + +```python +import sys +import logging +from azure.maps.route import MapsRouteClient + +# Create a logger for the 'azure.maps.route' SDK +logger = logging.getLogger('azure.maps.route') +logger.setLevel(logging.DEBUG) + +# Configure a console output +handler = logging.StreamHandler(stream=sys.stdout) +logger.addHandler(handler) + +``` + +### Additional + +Still running into issues? If you encounter any bugs or have suggestions, please file an issue in the [Issues]() section of the project. + +## Next steps + +### More sample code + +Get started with our [Maps Route samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route/samples) ([Async Version samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route/samples/async_samples)). + +Several Azure Maps Route Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Maps Route + +```bash +set AZURE_SUBSCRIPTION_KEY="" + +pip install azure-maps-route --pre + +python samples/sample_authentication.py +python sample/sample_get_route_range.py +python samples/sample_get_route_directions.py +python samples/sample_request_route_matrix.py +python samples/async_samples/sample_authentication_async.py +python samples/async_samples/sample_get_route_range_async.py +python samples/async_samples/sample_request_route_matrix_async.py +python samples/async_samples/sample_get_route_directions_async.py +``` + +> Notes: `--pre` flag can be optionally added, it is to include pre-release and development versions for `pip install`. By default, `pip` only finds stable versions. + +Further detail please refer to [Samples Introduction](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/maps/azure-maps-route/samples/README.md) + +### Additional documentation + +For more extensive documentation on Azure Maps Route, see the [Azure Maps Route documentation](https://docs.microsoft.com/rest/api/maps/route) on docs.microsoft.com. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + + +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity +[azure_portal]: https://portal.azure.com +[azure_cli]: https://docs.microsoft.com/cli/azure +[azure-key-credential]: https://aka.ms/azsdk/python/core/azurekeycredential +[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential +[register_aad_app]: https://docs.microsoft.com/powershell/module/Az.Resources/New-AzADApplication?view=azps-8.0.0 +[maps_authentication_aad]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication +[create_new_application_registration]: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/applicationsListBlade/quickStartType/AspNetWebAppQuickstartPage/sourceType/docs +[manage_aad_auth_page]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication +[how_to_manage_authentication]: https://docs.microsoft.com/azure/azure-maps/how-to-manage-authentication#view-authentication-details diff --git a/sdk/maps/azure-maps-route/azure/__init__.py b/sdk/maps/azure-maps-route/azure/__init__.py new file mode 100644 index 000000000000..8db66d3d0f0f --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/maps/azure-maps-route/azure/maps/__init__.py b/sdk/maps/azure-maps-route/azure/maps/__init__.py new file mode 100644 index 000000000000..8db66d3d0f0f --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/__init__.py new file mode 100644 index 000000000000..596ea9c88588 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/__init__.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._version import VERSION +from ._route_client import MapsRouteClient + +__all__ = [ + 'MapsRouteClient' +] +__version__ = VERSION diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_base_client.py b/sdk/maps/azure-maps-route/azure/maps/route/_base_client.py new file mode 100644 index 000000000000..2e02f88423d4 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_base_client.py @@ -0,0 +1,48 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from typing import Union, Any +from azure.core.pipeline.policies import AzureKeyCredentialPolicy +from azure.core.credentials import AzureKeyCredential, TokenCredential +from ._generated import MapsRouteClient as _MapsRouteClient +from ._version import VERSION + +# To check the credential is either AzureKeyCredential or TokenCredential +def _authentication_policy(credential): + authentication_policy = None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if isinstance(credential, AzureKeyCredential): + authentication_policy = AzureKeyCredentialPolicy( + name="subscription-key", credential=credential + ) + elif credential is not None and not hasattr(credential, "get_token"): + raise TypeError( + "Unsupported credential: {}. Use an instance of AzureKeyCredential " + "or a token credential from azure.identity".format(type(credential)) + ) + return authentication_policy + +class MapsRouteClientBase: + def __init__( + self, + credential: Union[AzureKeyCredential, TokenCredential], + **kwargs: Any + ) -> None: + + self._maps_client = _MapsRouteClient( + credential=credential, # type: ignore + api_version=kwargs.pop("api_version", VERSION), + authentication_policy=kwargs.pop("authentication_policy", _authentication_policy(credential)), + **kwargs + ) + self._route_client = self._maps_client.route + + def __enter__(self): + self._maps_client.__enter__() # pylint:disable=no-member + return self + + def __exit__(self, *args): + self._maps_client.__exit__(*args) # pylint:disable=no-member diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/__init__.py new file mode 100644 index 000000000000..3a3ceaee1f06 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/__init__.py @@ -0,0 +1,24 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._client import MapsRouteClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["MapsRouteClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_client.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_client.py new file mode 100644 index 000000000000..7d3d332a4801 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_client.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Optional, TYPE_CHECKING + +from azure.core import PipelineClient +from azure.core.rest import HttpRequest, HttpResponse + +from . import models +from ._configuration import MapsRouteClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import RouteOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MapsRouteClient: # pylint: disable=client-accepts-api-version-keyword + """Azure Maps Route REST APIs. + + :ivar route: RouteOperations operations + :vartype route: azure.maps.route.operations.RouteOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param client_id: Specifies which account is intended for usage in conjunction with the Azure + AD security model. It represents a unique ID for the Azure Maps account and can be retrieved + from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see + the following `articles `_ for guidance. Default value is None. + :type client_id: str + :keyword endpoint: Service URL. Default value is "https://atlas.microsoft.com". + :paramtype endpoint: str + :keyword api_version: Api Version. Default value is "1.0". Note that overriding this default + value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + client_id: Optional[str] = None, + *, + endpoint: str = "https://atlas.microsoft.com", + **kwargs: Any + ) -> None: + self._config = MapsRouteClientConfiguration(credential=credential, client_id=client_id, **kwargs) + self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.route = RouteOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> MapsRouteClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_configuration.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_configuration.py new file mode 100644 index 000000000000..e92a332e50b4 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_configuration.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class MapsRouteClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for MapsRouteClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param client_id: Specifies which account is intended for usage in conjunction with the Azure + AD security model. It represents a unique ID for the Azure Maps account and can be retrieved + from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see + the following `articles `_ for guidance. Default value is None. + :type client_id: str + :keyword api_version: Api Version. Default value is "1.0". Note that overriding this default + value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", client_id: Optional[str] = None, **kwargs: Any) -> None: + super(MapsRouteClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "1.0") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.client_id = client_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://atlas.microsoft.com/.default"]) + kwargs.setdefault("sdk_moniker", "maps-route/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_serialization.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_vendor.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_vendor.py new file mode 100644 index 000000000000..54f238858ed8 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_vendor.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/_version.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_version.py new file mode 100644 index 000000000000..b9995fb385b0 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0-preview" diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/__init__.py new file mode 100644 index 000000000000..8fb07df07c83 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._client import MapsRouteClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["MapsRouteClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_client.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_client.py new file mode 100644 index 000000000000..331237b014f9 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_client.py @@ -0,0 +1,93 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, Optional, TYPE_CHECKING + +from azure.core import AsyncPipelineClient +from azure.core.rest import AsyncHttpResponse, HttpRequest + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import MapsRouteClientConfiguration +from .operations import RouteOperations + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MapsRouteClient: # pylint: disable=client-accepts-api-version-keyword + """Azure Maps Route REST APIs. + + :ivar route: RouteOperations operations + :vartype route: azure.maps.route.aio.operations.RouteOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param client_id: Specifies which account is intended for usage in conjunction with the Azure + AD security model. It represents a unique ID for the Azure Maps account and can be retrieved + from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see + the following `articles `_ for guidance. Default value is None. + :type client_id: str + :keyword endpoint: Service URL. Default value is "https://atlas.microsoft.com". + :paramtype endpoint: str + :keyword api_version: Api Version. Default value is "1.0". Note that overriding this default + value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + client_id: Optional[str] = None, + *, + endpoint: str = "https://atlas.microsoft.com", + **kwargs: Any + ) -> None: + self._config = MapsRouteClientConfiguration(credential=credential, client_id=client_id, **kwargs) + self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.route = RouteOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MapsRouteClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_configuration.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_configuration.py new file mode 100644 index 000000000000..28f1bfdf933c --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_configuration.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from .._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class MapsRouteClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for MapsRouteClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param client_id: Specifies which account is intended for usage in conjunction with the Azure + AD security model. It represents a unique ID for the Azure Maps account and can be retrieved + from the Azure Maps management plane Account API. To use Azure AD security in Azure Maps see + the following `articles `_ for guidance. Default value is None. + :type client_id: str + :keyword api_version: Api Version. Default value is "1.0". Note that overriding this default + value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", client_id: Optional[str] = None, **kwargs: Any) -> None: + super(MapsRouteClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "1.0") # type: str + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.credential = credential + self.client_id = client_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://atlas.microsoft.com/.default"]) + kwargs.setdefault("sdk_moniker", "maps-route/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/__init__.py new file mode 100644 index 000000000000..08df5df8aeba --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import RouteOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "RouteOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_operations.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_operations.py new file mode 100644 index 000000000000..ef3a08d1b1b1 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_operations.py @@ -0,0 +1,5961 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import datetime +from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.polling.async_base_polling import AsyncLROBasePolling +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ...operations._operations import ( + build_route_get_route_directions_batch_request, + build_route_get_route_directions_request, + build_route_get_route_directions_with_additional_parameters_request, + build_route_get_route_matrix_request, + build_route_get_route_range_request, + build_route_request_route_directions_batch_request, + build_route_request_route_directions_batch_sync_request, + build_route_request_route_matrix_request, + build_route_request_route_matrix_sync_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class RouteOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.maps.route.aio.MapsRouteClient`'s + :attr:`route` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _request_route_matrix_initial( + self, + route_matrix_query: Union[_models.RouteMatrixQuery, IO], + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + **kwargs: Any + ) -> Optional[_models.RouteMatrixResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_matrix_query, (IO, bytes)): + _content = route_matrix_query + else: + _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") + + request = build_route_request_route_matrix_request( + format=format, + wait_for_results=wait_for_results, + compute_travel_time=compute_travel_time, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @overload + async def begin_request_route_matrix( + self, + route_matrix_query: _models.RouteMatrixQuery, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_request_route_matrix( + self, + route_matrix_query: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_request_route_matrix( + self, + route_matrix_query: Union[_models.RouteMatrixQuery, IO], + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + **kwargs: Any + ) -> AsyncLROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Is either a model type or a IO type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._request_route_matrix_initial( # type: ignore + route_matrix_query=route_matrix_query, + format=format, + wait_for_results=wait_for_results, + compute_travel_time=compute_travel_time, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + async def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Optional[_models.RouteMatrixResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + + request = build_route_get_route_matrix_request( + matrix_id=matrix_id, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace_async + async def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> AsyncLROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param matrix_id: Matrix id received after the Matrix Route request was accepted successfully. + Required. + :type matrix_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._get_route_matrix_initial( # type: ignore + matrix_id=matrix_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + @overload + async def request_route_matrix_sync( + self, + route_matrix_query: _models.RouteMatrixQuery, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteMatrixResult: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def request_route_matrix_sync( + self, + route_matrix_query: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteMatrixResult: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def request_route_matrix_sync( + self, + route_matrix_query: Union[_models.RouteMatrixQuery, IO], + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + **kwargs: Any + ) -> _models.RouteMatrixResult: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Is either a model type or a IO type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + 408: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_matrix_query, (IO, bytes)): + _content = route_matrix_query + else: + _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") + + request = build_route_request_route_matrix_sync_request( + format=format, + wait_for_results=wait_for_results, + compute_travel_time=compute_travel_time, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + @distributed_trace_async + async def get_route_directions( + self, + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + vehicle_axle_weight: int = 0, + vehicle_width: float = 0, + vehicle_height: float = 0, + vehicle_length: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. + Proper nouns (the names of streets, plazas, etc.) are returned in the specified language, or + if that is not available, they are returned in an available language that is close to it. + Allowed values are (a subset of) the IETF language tags. The currently supported languages are + listed in the `Supported languages section + `_. + + Default value: en-GB. Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + + request = build_route_get_route_directions_request( + format=format, + route_points=route_points, + max_alternatives=max_alternatives, + alternative_type=alternative_type, + min_deviation_distance=min_deviation_distance, + arrive_at=arrive_at, + depart_at=depart_at, + min_deviation_time=min_deviation_time, + instructions_type=instructions_type, + language=language, + compute_best_waypoint_order=compute_best_waypoint_order, + route_representation_for_best_order=route_representation_for_best_order, + compute_travel_time=compute_travel_time, + vehicle_heading=vehicle_heading, + report=report, + filter_section_type=filter_section_type, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_width=vehicle_width, + vehicle_height=vehicle_height, + vehicle_length=vehicle_length, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + is_commercial_vehicle=is_commercial_vehicle, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + vehicle_engine_type=vehicle_engine_type, + constant_speed_consumption_in_liters_per_hundred_km=constant_speed_consumption_in_liters_per_hundred_km, + current_fuel_in_liters=current_fuel_in_liters, + auxiliary_power_in_liters_per_hour=auxiliary_power_in_liters_per_hour, + fuel_energy_density_in_megajoules_per_liter=fuel_energy_density_in_megajoules_per_liter, + acceleration_efficiency=acceleration_efficiency, + deceleration_efficiency=deceleration_efficiency, + uphill_efficiency=uphill_efficiency, + downhill_efficiency=downhill_efficiency, + constant_speed_consumption_in_kw_h_per_hundred_km=constant_speed_consumption_in_kw_h_per_hundred_km, + current_charge_in_kw_h=current_charge_in_kw_h, + max_charge_in_kw_h=max_charge_in_kw_h, + auxiliary_power_in_kw=auxiliary_power_in_kw, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteDirections", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + @overload + async def get_route_directions_with_additional_parameters( + self, + route_direction_parameters: _models.RouteDirectionParameters, + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of a vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param route_direction_parameters: Used for reconstructing a route and for calculating zero or + more alternative routes to this reference route. The provided sequence of coordinates is used + as input for route reconstruction. The alternative routes are calculated between the origin + and destination points specified in the base path parameter locations. If both + minDeviationDistance and minDeviationTime are set to zero, then these origin and destination + points are expected to be at (or very near) the beginning and end of the reference route, + respectively. Intermediate locations (waypoints) are not supported when using + supportingPoints. + + Setting at least one of minDeviationDistance or minDeviationTime to a value greater than zero + has the following consequences: + + + * The origin point of the calculateRoute request must be on (or very near) the input reference + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. + * The values of minDeviationDistance and minDeviationTime determine how far alternative routes + will be guaranteed to follow the reference route from the origin point onwards. + * The route must use departAt. + * The vehicleHeading is ignored. Required. + :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def get_route_directions_with_additional_parameters( + self, + route_direction_parameters: IO, + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of a vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param route_direction_parameters: Used for reconstructing a route and for calculating zero or + more alternative routes to this reference route. The provided sequence of coordinates is used + as input for route reconstruction. The alternative routes are calculated between the origin + and destination points specified in the base path parameter locations. If both + minDeviationDistance and minDeviationTime are set to zero, then these origin and destination + points are expected to be at (or very near) the beginning and end of the reference route, + respectively. Intermediate locations (waypoints) are not supported when using + supportingPoints. + + Setting at least one of minDeviationDistance or minDeviationTime to a value greater than zero + has the following consequences: + + + * The origin point of the calculateRoute request must be on (or very near) the input reference + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. + * The values of minDeviationDistance and minDeviationTime determine how far alternative routes + will be guaranteed to follow the reference route from the origin point onwards. + * The route must use departAt. + * The vehicleHeading is ignored. Required. + :type route_direction_parameters: IO + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def get_route_directions_with_additional_parameters( + self, + route_direction_parameters: Union[_models.RouteDirectionParameters, IO], + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of a vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param route_direction_parameters: Used for reconstructing a route and for calculating zero or + more alternative routes to this reference route. The provided sequence of coordinates is used + as input for route reconstruction. The alternative routes are calculated between the origin + and destination points specified in the base path parameter locations. If both + minDeviationDistance and minDeviationTime are set to zero, then these origin and destination + points are expected to be at (or very near) the beginning and end of the reference route, + respectively. Intermediate locations (waypoints) are not supported when using + supportingPoints. + + Setting at least one of minDeviationDistance or minDeviationTime to a value greater than zero + has the following consequences: + + + * The origin point of the calculateRoute request must be on (or very near) the input reference + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. + * The values of minDeviationDistance and minDeviationTime determine how far alternative routes + will be guaranteed to follow the reference route from the origin point onwards. + * The route must use departAt. + * The vehicleHeading is ignored. Is either a model type or a IO type. Required. + :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters or IO + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_direction_parameters, (IO, bytes)): + _content = route_direction_parameters + else: + _json = self._serialize.body(route_direction_parameters, "RouteDirectionParameters") + + request = build_route_get_route_directions_with_additional_parameters_request( + format=format, + route_points=route_points, + max_alternatives=max_alternatives, + alternative_type=alternative_type, + min_deviation_distance=min_deviation_distance, + min_deviation_time=min_deviation_time, + instructions_type=instructions_type, + language=language, + compute_best_waypoint_order=compute_best_waypoint_order, + route_representation_for_best_order=route_representation_for_best_order, + compute_travel_time=compute_travel_time, + vehicle_heading=vehicle_heading, + report=report, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + is_commercial_vehicle=is_commercial_vehicle, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + vehicle_engine_type=vehicle_engine_type, + constant_speed_consumption_in_liters_per_hundred_km=constant_speed_consumption_in_liters_per_hundred_km, + current_fuel_in_liters=current_fuel_in_liters, + auxiliary_power_in_liters_per_hour=auxiliary_power_in_liters_per_hour, + fuel_energy_density_in_megajoules_per_liter=fuel_energy_density_in_megajoules_per_liter, + acceleration_efficiency=acceleration_efficiency, + deceleration_efficiency=deceleration_efficiency, + uphill_efficiency=uphill_efficiency, + downhill_efficiency=downhill_efficiency, + constant_speed_consumption_in_kw_h_per_hundred_km=constant_speed_consumption_in_kw_h_per_hundred_km, + current_charge_in_kw_h=current_charge_in_kw_h, + max_charge_in_kw_h=max_charge_in_kw_h, + auxiliary_power_in_kw=auxiliary_power_in_kw, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteDirections", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + @distributed_trace_async + async def get_route_range( + self, + format: Union[str, _models.ResponseFormat] = "json", + *, + query: List[float], + fuel_budget_in_liters: Optional[float] = None, + energy_budget_in_kw_h: Optional[float] = None, + time_budget_in_sec: Optional[float] = None, + distance_budget_in_meters: Optional[float] = None, + depart_at: Optional[datetime.datetime] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + use_traffic_data: Optional[bool] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + vehicle_axle_weight: int = 0, + vehicle_width: float = 0, + vehicle_height: float = 0, + vehicle_length: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + **kwargs: Any + ) -> _models.RouteRangeResult: + """**Route Range (Isochrone) API** + + **Applies to**\ : see pricing `tiers `_. + + This service will calculate a set of locations that can be reached from the origin point based + on fuel, energy, time or distance budget that is specified. A polygon boundary (or Isochrone) + is returned in a counterclockwise orientation as well as the precise polygon center which was + the result of the origin point. + + The returned polygon can be used for further processing such as `Search Inside Geometry + `_ to search for + POIs within the provided Isochrone. + + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword query: The Coordinate from which the range calculation should start. Required. + :paramtype query: list[float] + :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can + be travelled using the specified Combustion Consumption Model.:code:`
` When + fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption + Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype fuel_budget_in_liters: float + :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines + maximal range which can be travelled using the specified Electric Consumption + Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype energy_budget_in_kw_h: float + :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be + travelled using driving time. The Consumption Model will only affect the range when routeType + is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype time_budget_in_sec: float + :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range + which can be travelled using driving distance. The Consumption Model will only affect the + range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype distance_budget_in_meters: float + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :return: RouteRangeResult + :rtype: ~azure.maps.route.models.RouteRangeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteRangeResult] + + request = build_route_get_route_range_request( + format=format, + query=query, + fuel_budget_in_liters=fuel_budget_in_liters, + energy_budget_in_kw_h=energy_budget_in_kw_h, + time_budget_in_sec=time_budget_in_sec, + distance_budget_in_meters=distance_budget_in_meters, + depart_at=depart_at, + route_type=route_type, + use_traffic_data=use_traffic_data, + avoid=avoid, + travel_mode=travel_mode, + incline_level=incline_level, + windingness=windingness, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_width=vehicle_width, + vehicle_height=vehicle_height, + vehicle_length=vehicle_length, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + is_commercial_vehicle=is_commercial_vehicle, + vehicle_load_type=vehicle_load_type, + vehicle_engine_type=vehicle_engine_type, + constant_speed_consumption_in_liters_per_hundred_km=constant_speed_consumption_in_liters_per_hundred_km, + current_fuel_in_liters=current_fuel_in_liters, + auxiliary_power_in_liters_per_hour=auxiliary_power_in_liters_per_hour, + fuel_energy_density_in_megajoules_per_liter=fuel_energy_density_in_megajoules_per_liter, + acceleration_efficiency=acceleration_efficiency, + deceleration_efficiency=deceleration_efficiency, + uphill_efficiency=uphill_efficiency, + downhill_efficiency=downhill_efficiency, + constant_speed_consumption_in_kw_h_per_hundred_km=constant_speed_consumption_in_kw_h_per_hundred_km, + current_charge_in_kw_h=current_charge_in_kw_h, + max_charge_in_kw_h=max_charge_in_kw_h, + auxiliary_power_in_kw=auxiliary_power_in_kw, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteRangeResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + async def _request_route_directions_batch_initial( + self, + route_directions_batch_queries: Union[_models.BatchRequest, IO], + format: Union[str, _models.JsonFormat] = "json", + **kwargs: Any + ) -> Optional[_models.RouteDirectionsBatchResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_directions_batch_queries, (IO, bytes)): + _content = route_directions_batch_queries + else: + _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") + + request = build_route_request_route_directions_batch_request( + format=format, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @overload + async def begin_request_route_directions_batch( + self, + route_directions_batch_queries: _models.BatchRequest, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Asynchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex route + requests + + + * It allows the retrieval of results in a separate call (multiple downloads are possible). + * The asynchronous API is optimized for reliability and is not expected to run into a timeout. + * The number of batch items is limited to **700** for this API. + + When you make a request by using async request, by default the service returns a 202 response + code along a redirect URL in the Location field of the response header. This URL should be + checked periodically until the response data or error information is available. + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + Please note that asynchronous batch request is a long-running request. Here's a typical + sequence of operations: + + + #. Client sends a Route Directions Batch ``POST`` request to Azure Maps + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request has been accepted. + + HTTP ``Error`` - There was an error processing your Batch request. This could either be a + ``400 Bad Request`` or any other ``Error`` status code. + + + #. + If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: + + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\ ) to the *status URI* before running it. :code:`
` + + + #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the + batch results. + + POST Body for Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To send the *route directions* queries you will use a ``POST`` request where the request body + will contain the ``batchItems`` array in ``json`` format and the ``Content-Type`` header will + be set to ``application/json``. Here's a sample request body containing 3 *route directions* + queries: + + .. code-block:: json + + { + "batchItems": [ + { "query": + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, + { "query": + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } + ] + } + + A *route directions* query in a batch is just a partial URL *without* the protocol, base URL, + path, api-version and subscription-key. It can accept any of the supported *route directions* + `URI parameters + `_. The + string values in the *route directions* query must be properly escaped (e.g. " character should + be escaped with ) and it should also be properly URL-encoded. + + The async API allows caller to batch up to **700** queries and sync API up to **100** queries, + and the batch should contain at least **1** query. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_request_route_directions_batch( + self, + route_directions_batch_queries: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Asynchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex route + requests + + + * It allows the retrieval of results in a separate call (multiple downloads are possible). + * The asynchronous API is optimized for reliability and is not expected to run into a timeout. + * The number of batch items is limited to **700** for this API. + + When you make a request by using async request, by default the service returns a 202 response + code along a redirect URL in the Location field of the response header. This URL should be + checked periodically until the response data or error information is available. + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + Please note that asynchronous batch request is a long-running request. Here's a typical + sequence of operations: + + + #. Client sends a Route Directions Batch ``POST`` request to Azure Maps + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request has been accepted. + + HTTP ``Error`` - There was an error processing your Batch request. This could either be a + ``400 Bad Request`` or any other ``Error`` status code. + + + #. + If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: + + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\ ) to the *status URI* before running it. :code:`
` + + + #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the + batch results. + + POST Body for Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To send the *route directions* queries you will use a ``POST`` request where the request body + will contain the ``batchItems`` array in ``json`` format and the ``Content-Type`` header will + be set to ``application/json``. Here's a sample request body containing 3 *route directions* + queries: + + .. code-block:: json + + { + "batchItems": [ + { "query": + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, + { "query": + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } + ] + } + + A *route directions* query in a batch is just a partial URL *without* the protocol, base URL, + path, api-version and subscription-key. It can accept any of the supported *route directions* + `URI parameters + `_. The + string values in the *route directions* query must be properly escaped (e.g. " character should + be escaped with ) and it should also be properly URL-encoded. + + The async API allows caller to batch up to **700** queries and sync API up to **100** queries, + and the batch should contain at least **1** query. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_request_route_directions_batch( + self, + route_directions_batch_queries: Union[_models.BatchRequest, IO], + format: Union[str, _models.JsonFormat] = "json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Asynchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex route + requests + + + * It allows the retrieval of results in a separate call (multiple downloads are possible). + * The asynchronous API is optimized for reliability and is not expected to run into a timeout. + * The number of batch items is limited to **700** for this API. + + When you make a request by using async request, by default the service returns a 202 response + code along a redirect URL in the Location field of the response header. This URL should be + checked periodically until the response data or error information is available. + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + Please note that asynchronous batch request is a long-running request. Here's a typical + sequence of operations: + + + #. Client sends a Route Directions Batch ``POST`` request to Azure Maps + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request has been accepted. + + HTTP ``Error`` - There was an error processing your Batch request. This could either be a + ``400 Bad Request`` or any other ``Error`` status code. + + + #. + If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: + + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\ ) to the *status URI* before running it. :code:`
` + + + #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the + batch results. + + POST Body for Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To send the *route directions* queries you will use a ``POST`` request where the request body + will contain the ``batchItems`` array in ``json`` format and the ``Content-Type`` header will + be set to ``application/json``. Here's a sample request body containing 3 *route directions* + queries: + + .. code-block:: json + + { + "batchItems": [ + { "query": + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, + { "query": + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } + ] + } + + A *route directions* query in a batch is just a partial URL *without* the protocol, base URL, + path, api-version and subscription-key. It can accept any of the supported *route directions* + `URI parameters + `_. The + string values in the *route directions* query must be properly escaped (e.g. " character should + be escaped with ) and it should also be properly URL-encoded. + + The async API allows caller to batch up to **700** queries and sync API up to **100** queries, + and the batch should contain at least **1** query. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Is either a model type or a IO type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._request_route_directions_batch_initial( # type: ignore + route_directions_batch_queries=route_directions_batch_queries, + format=format, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + async def _get_route_directions_batch_initial( + self, batch_id: str, **kwargs: Any + ) -> Optional[_models.RouteDirectionsBatchResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + + request = build_route_get_route_directions_batch_request( + batch_id=batch_id, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace_async + async def begin_get_route_directions_batch( + self, batch_id: str, **kwargs: Any + ) -> AsyncLROPoller[_models.RouteDirectionsBatchResult]: + """**Applies to**\ : see pricing `tiers `_. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param batch_id: Batch id for querying the operation. Required. + :type batch_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False + for this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._get_route_directions_batch_initial( # type: ignore + batch_id=batch_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + @overload + async def request_route_directions_batch_sync( + self, + route_directions_batch_queries: _models.BatchRequest, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirectionsBatchResult: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Synchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Synchronous API is recommended for lightweight batch requests. When the service receives a + request, it will respond as soon as the batch items are calculated and there will be no + possibility to retrieve the results later. The Synchronous API will return a timeout error (a + 408 response) if the request takes longer than 60 seconds. The number of batch items is limited + to **100** for this API. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirectionsBatchResult + :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def request_route_directions_batch_sync( + self, + route_directions_batch_queries: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirectionsBatchResult: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Synchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Synchronous API is recommended for lightweight batch requests. When the service receives a + request, it will respond as soon as the batch items are calculated and there will be no + possibility to retrieve the results later. The Synchronous API will return a timeout error (a + 408 response) if the request takes longer than 60 seconds. The number of batch items is limited + to **100** for this API. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirectionsBatchResult + :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def request_route_directions_batch_sync( + self, + route_directions_batch_queries: Union[_models.BatchRequest, IO], + format: Union[str, _models.JsonFormat] = "json", + **kwargs: Any + ) -> _models.RouteDirectionsBatchResult: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Synchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Synchronous API is recommended for lightweight batch requests. When the service receives a + request, it will respond as soon as the batch items are calculated and there will be no + possibility to retrieve the results later. The Synchronous API will return a timeout error (a + 408 response) if the request takes longer than 60 seconds. The number of batch items is limited + to **100** for this API. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Is either a model type or a IO type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: RouteDirectionsBatchResult + :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + 408: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_directions_batch_queries, (IO, bytes)): + _content = route_directions_batch_queries + else: + _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") + + request = build_route_request_route_directions_batch_sync_request( + format=format, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/__init__.py new file mode 100644 index 000000000000..ad96766b2ce1 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/__init__.py @@ -0,0 +1,173 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models import BatchRequest +from ._models import BatchRequestItem +from ._models import BatchResult +from ._models import BatchResultItem +from ._models import BatchResultSummary +from ._models import EffectiveSetting +from ._models import ErrorAdditionalInfo +from ._models import ErrorDetail +from ._models import ErrorResponse +from ._models import GeoJsonFeature +from ._models import GeoJsonFeatureCollection +from ._models import GeoJsonFeatureCollectionData +from ._models import GeoJsonFeatureData +from ._models import GeoJsonGeometry +from ._models import GeoJsonGeometryCollection +from ._models import GeoJsonGeometryCollectionData +from ._models import GeoJsonLineString +from ._models import GeoJsonLineStringData +from ._models import GeoJsonMultiLineString +from ._models import GeoJsonMultiLineStringData +from ._models import GeoJsonMultiPoint +from ._models import GeoJsonMultiPointData +from ._models import GeoJsonMultiPolygon +from ._models import GeoJsonMultiPolygonData +from ._models import GeoJsonObject +from ._models import GeoJsonPoint +from ._models import GeoJsonPointData +from ._models import GeoJsonPolygon +from ._models import GeoJsonPolygonData +from ._models import LatLongPair +from ._models import Route +from ._models import RouteDirectionParameters +from ._models import RouteDirections +from ._models import RouteDirectionsBatchItem +from ._models import RouteDirectionsBatchItemResponse +from ._models import RouteDirectionsBatchResult +from ._models import RouteGuidance +from ._models import RouteInstruction +from ._models import RouteInstructionGroup +from ._models import RouteLeg +from ._models import RouteLegSummary +from ._models import RouteMatrix +from ._models import RouteMatrixQuery +from ._models import RouteMatrixResult +from ._models import RouteMatrixResultResponse +from ._models import RouteMatrixSummary +from ._models import RouteOptimizedWaypoint +from ._models import RouteRange +from ._models import RouteRangeResult +from ._models import RouteReport +from ._models import RouteSection +from ._models import RouteSectionTec +from ._models import RouteSectionTecCause +from ._models import RouteSummary + +from ._enums import AlternativeRouteType +from ._enums import ComputeTravelTime +from ._enums import DelayMagnitude +from ._enums import DrivingSide +from ._enums import GeoJsonObjectType +from ._enums import GuidanceInstructionType +from ._enums import GuidanceManeuver +from ._enums import InclineLevel +from ._enums import JsonFormat +from ._enums import JunctionType +from ._enums import Report +from ._enums import ResponseFormat +from ._enums import ResponseSectionType +from ._enums import ResponseTravelMode +from ._enums import RouteAvoidType +from ._enums import RouteInstructionsType +from ._enums import RouteRepresentationForBestOrder +from ._enums import RouteType +from ._enums import SectionType +from ._enums import SimpleCategory +from ._enums import TravelMode +from ._enums import VehicleEngineType +from ._enums import VehicleLoadType +from ._enums import WindingnessLevel +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BatchRequest", + "BatchRequestItem", + "BatchResult", + "BatchResultItem", + "BatchResultSummary", + "EffectiveSetting", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "GeoJsonFeature", + "GeoJsonFeatureCollection", + "GeoJsonFeatureCollectionData", + "GeoJsonFeatureData", + "GeoJsonGeometry", + "GeoJsonGeometryCollection", + "GeoJsonGeometryCollectionData", + "GeoJsonLineString", + "GeoJsonLineStringData", + "GeoJsonMultiLineString", + "GeoJsonMultiLineStringData", + "GeoJsonMultiPoint", + "GeoJsonMultiPointData", + "GeoJsonMultiPolygon", + "GeoJsonMultiPolygonData", + "GeoJsonObject", + "GeoJsonPoint", + "GeoJsonPointData", + "GeoJsonPolygon", + "GeoJsonPolygonData", + "LatLongPair", + "Route", + "RouteDirectionParameters", + "RouteDirections", + "RouteDirectionsBatchItem", + "RouteDirectionsBatchItemResponse", + "RouteDirectionsBatchResult", + "RouteGuidance", + "RouteInstruction", + "RouteInstructionGroup", + "RouteLeg", + "RouteLegSummary", + "RouteMatrix", + "RouteMatrixQuery", + "RouteMatrixResult", + "RouteMatrixResultResponse", + "RouteMatrixSummary", + "RouteOptimizedWaypoint", + "RouteRange", + "RouteRangeResult", + "RouteReport", + "RouteSection", + "RouteSectionTec", + "RouteSectionTecCause", + "RouteSummary", + "AlternativeRouteType", + "ComputeTravelTime", + "DelayMagnitude", + "DrivingSide", + "GeoJsonObjectType", + "GuidanceInstructionType", + "GuidanceManeuver", + "InclineLevel", + "JsonFormat", + "JunctionType", + "Report", + "ResponseFormat", + "ResponseSectionType", + "ResponseTravelMode", + "RouteAvoidType", + "RouteInstructionsType", + "RouteRepresentationForBestOrder", + "RouteType", + "SectionType", + "SimpleCategory", + "TravelMode", + "VehicleEngineType", + "VehicleLoadType", + "WindingnessLevel", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_enums.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_enums.py new file mode 100644 index 000000000000..3136f5e0c51b --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_enums.py @@ -0,0 +1,461 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AlternativeRouteType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """AlternativeRouteType.""" + + #: Allow any alternative route to be returned irrespective of how it compares to the reference + #: route in terms of optimality. + ANY_ROUTE = "anyRoute" + #: Return an alternative route only if it is better than the reference route according to the + #: given planning criteria. + BETTER_ROUTE = "betterRoute" + + +class ComputeTravelTime(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ComputeTravelTime.""" + + #: Does not compute additional travel times. + NONE = "none" + #: Computes travel times for all types of traffic information and specifies all results in the + #: fields noTrafficTravelTimeInSeconds, historicTrafficTravelTimeInSeconds and + #: liveTrafficIncidentsTravelTimeInSeconds being included in the summaries in the route response. + ALL = "all" + + +class DelayMagnitude(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The magnitude of delay caused by the incident. These values correspond to the values of the + response field ty of the `Get Traffic Incident Detail API + `_. + """ + + #: Unknown. + UNKNOWN = "0" + #: Minor. + MINOR = "1" + #: Moderate. + MODERATE = "2" + #: Major. + MAJOR = "3" + #: Undefined, used for road closures and other indefinite delays. + UNDEFINED = "4" + + +class DrivingSide(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates left-hand vs. right-hand side driving at the point of the maneuver.""" + + #: Left side. + LEFT = "LEFT" + #: Right side. + RIGHT = "RIGHT" + + +class GeoJsonObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, + MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and + FeatureCollection. + """ + + #: ``GeoJSON Point`` geometry. + GEO_JSON_POINT = "Point" + #: ``GeoJSON MultiPoint`` geometry. + GEO_JSON_MULTI_POINT = "MultiPoint" + #: ``GeoJSON LineString`` geometry. + GEO_JSON_LINE_STRING = "LineString" + #: ``GeoJSON MultiLineString`` geometry. + GEO_JSON_MULTI_LINE_STRING = "MultiLineString" + #: ``GeoJSON Polygon`` geometry. + GEO_JSON_POLYGON = "Polygon" + #: ``GeoJSON MultiPolygon`` geometry. + GEO_JSON_MULTI_POLYGON = "MultiPolygon" + #: ``GeoJSON GeometryCollection`` geometry. + GEO_JSON_GEOMETRY_COLLECTION = "GeometryCollection" + #: ``GeoJSON Feature`` object. + GEO_JSON_FEATURE = "Feature" + #: ``GeoJSON FeatureCollection`` object. + GEO_JSON_FEATURE_COLLECTION = "FeatureCollection" + + +class GuidanceInstructionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the instruction, e.g., turn or change of road form.""" + + #: Turn. + TURN = "TURN" + #: Road Change. + ROAD_CHANGE = "ROAD_CHANGE" + #: Departure location. + LOCATION_DEPARTURE = "LOCATION_DEPARTURE" + #: Arrival location. + LOCATION_ARRIVAL = "LOCATION_ARRIVAL" + #: Direction information. + DIRECTION_INFO = "DIRECTION_INFO" + #: Way point location. + LOCATION_WAYPOINT = "LOCATION_WAYPOINT" + + +class GuidanceManeuver(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """A code identifying the maneuver.""" + + #: You have arrived. + ARRIVE = "ARRIVE" + #: You have arrived. Your destination is on the left. + ARRIVE_LEFT = "ARRIVE_LEFT" + #: You have arrived. Your destination is on the right. + ARRIVE_RIGHT = "ARRIVE_RIGHT" + #: Leave. + DEPART = "DEPART" + #: Keep straight on. + STRAIGHT = "STRAIGHT" + #: Keep right. + KEEP_RIGHT = "KEEP_RIGHT" + #: Bear right. + BEAR_RIGHT = "BEAR_RIGHT" + #: Turn right. + TURN_RIGHT = "TURN_RIGHT" + #: Turn sharp right. + SHARP_RIGHT = "SHARP_RIGHT" + #: Keep left. + KEEP_LEFT = "KEEP_LEFT" + #: Bear left. + BEAR_LEFT = "BEAR_LEFT" + #: Turn left. + TURN_LEFT = "TURN_LEFT" + #: Turn sharp left. + SHARP_LEFT = "SHARP_LEFT" + #: Make a U-turn. + MAKE_U_TURN = "MAKE_UTURN" + #: Take the motorway. + ENTER_MOTORWAY = "ENTER_MOTORWAY" + #: Take the freeway. + ENTER_FREEWAY = "ENTER_FREEWAY" + #: Take the highway. + ENTER_HIGHWAY = "ENTER_HIGHWAY" + #: Take the exit. + TAKE_EXIT = "TAKE_EXIT" + #: Take the left exit. + MOTORWAY_EXIT_LEFT = "MOTORWAY_EXIT_LEFT" + #: Take the right exit. + MOTORWAY_EXIT_RIGHT = "MOTORWAY_EXIT_RIGHT" + #: Take the ferry. + TAKE_FERRY = "TAKE_FERRY" + #: Cross the roundabout. + ROUNDABOUT_CROSS = "ROUNDABOUT_CROSS" + #: At the roundabout take the exit on the right. + ROUNDABOUT_RIGHT = "ROUNDABOUT_RIGHT" + #: At the roundabout take the exit on the left. + ROUNDABOUT_LEFT = "ROUNDABOUT_LEFT" + #: Go around the roundabout. + ROUNDABOUT_BACK = "ROUNDABOUT_BACK" + #: Try to make a U-turn. + TRY_MAKE_U_TURN = "TRY_MAKE_UTURN" + #: Follow. + FOLLOW = "FOLLOW" + #: Switch to the parallel road. + SWITCH_PARALLEL_ROAD = "SWITCH_PARALLEL_ROAD" + #: Switch to the main road. + SWITCH_MAIN_ROAD = "SWITCH_MAIN_ROAD" + #: Take the ramp. + ENTRANCE_RAMP = "ENTRANCE_RAMP" + #: You have reached the waypoint. It is on the left. + WAYPOINT_LEFT = "WAYPOINT_LEFT" + #: You have reached the waypoint. It is on the right. + WAYPOINT_RIGHT = "WAYPOINT_RIGHT" + #: You have reached the waypoint. + WAYPOINT_REACHED = "WAYPOINT_REACHED" + + +class InclineLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InclineLevel.""" + + #: low + LOW = "low" + #: normal + NORMAL = "normal" + #: high + HIGH = "high" + + +class JsonFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """JsonFormat.""" + + #: `The JavaScript Object Notation Data Interchange Format `_ + JSON = "json" + + +class JunctionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the junction where the maneuver takes place. For larger roundabouts, two separate + instructions are generated for entering and leaving the roundabout. + """ + + #: regular + REGULAR = "REGULAR" + #: roundabout + ROUNDABOUT = "ROUNDABOUT" + #: bifurcation + BIFURCATION = "BIFURCATION" + + +class Report(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Report.""" + + #: Reports the effective parameters or data used when calling the API. + EFFECTIVE_SETTINGS = "effectiveSettings" + + +class ResponseFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ResponseFormat.""" + + #: `The JavaScript Object Notation Data Interchange Format `_ + JSON = "json" + #: `The Extensible Markup Language `_ + XML = "xml" + + +class ResponseSectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Section types of the reported route response.""" + + #: Sections of the route that are cars or trains. + CAR_OR_TRAIN = "CAR_TRAIN" + #: Sections indicating which countries the route is in. + COUNTRY = "COUNTRY" + #: Sections of the route that are ferries. + FERRY = "FERRY" + #: Sections of the route that are motorways. + MOTORWAY = "MOTORWAY" + #: Sections of the route that are only suited for pedestrians. + PEDESTRIAN = "PEDESTRIAN" + #: Sections of the route that require a toll to be payed. + TOLL_ROAD = "TOLL_ROAD" + #: Sections of the route that require a toll vignette to be present. + TOLL_VIGNETTE = "TOLL_VIGNETTE" + #: Sections of the route that contain traffic information. + TRAFFIC = "TRAFFIC" + #: Sections in relation to the request parameter ``travelMode``. + TRAVEL_MODE = "TRAVEL_MODE" + #: Sections of the route that are tunnels. + TUNNEL = "TUNNEL" + #: Sections of the route that require use of carpool (HOV/High Occupancy Vehicle) lanes. + CARPOOL = "CARPOOL" + #: Sections of the route that are located within urban areas. + URBAN = "URBAN" + + +class ResponseTravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Travel mode for the calculated route. The value will be set to ``other`` if the requested mode + of transport is not possible in this section. + """ + + #: The returned routes are optimized for cars. + CAR = "car" + #: The returned routes are optimized for commercial vehicles, like for trucks. + TRUCK = "truck" + #: The returned routes are optimized for taxis. BETA functionality. + TAXI = "taxi" + #: The returned routes are optimized for buses, including the use of bus only lanes. BETA + #: functionality. + BUS = "bus" + #: The returned routes are optimized for vans. BETA functionality. + VAN = "van" + #: The returned routes are optimized for motorcycles. BETA functionality. + MOTORCYCLE = "motorcycle" + #: The returned routes are optimized for bicycles, including use of bicycle lanes. + BICYCLE = "bicycle" + #: The returned routes are optimized for pedestrians, including the use of sidewalks. + PEDESTRIAN = "pedestrian" + #: The given mode of transport is not possible in this section + OTHER = "other" + + +class RouteAvoidType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RouteAvoidType.""" + + #: Avoids toll roads. + TOLL_ROADS = "tollRoads" + #: Avoids motorways + MOTORWAYS = "motorways" + #: Avoids ferries + FERRIES = "ferries" + #: Avoids unpaved roads + UNPAVED_ROADS = "unpavedRoads" + #: Avoids routes that require the use of carpool (HOV/High Occupancy Vehicle) lanes. + CARPOOLS = "carpools" + #: Avoids using the same road multiple times. Most useful in conjunction with ``routeType``\ + #: =thrilling. + ALREADY_USED_ROADS = "alreadyUsedRoads" + #: Avoids border crossings in route calculation. + BORDER_CROSSINGS = "borderCrossings" + + +class RouteInstructionsType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RouteInstructionsType.""" + + #: Returns raw instruction data without human-readable messages. + CODED = "coded" + #: Returns raw instructions data with human-readable messages in plain text. + TEXT = "text" + #: Returns raw instruction data with tagged human-readable messages to permit formatting. A + #: human-readable message is built up from repeatable identified elements. These are tagged to + #: allow client applications to format them correctly. The following message components are tagged + #: when instructionsType=tagged: street, roadNumber, signpostText, exitNumber, + #: roundaboutExitNumber. + #: + #: Example of tagged 'Turn left' message:​ + #: + #: .. code-block:: + #: + #: Turn left onto A4/E19 + #: towards Den Haag + TAGGED = "tagged" + + +class RouteRepresentationForBestOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RouteRepresentationForBestOrder.""" + + #: Includes route geometry in the response. + POLYLINE = "polyline" + #: Summary as per polyline but excluding the point geometry elements for the routes in the + #: response. + SUMMARY_ONLY = "summaryOnly" + #: Includes only the optimized waypoint indices but does not include the route geometry in the + #: response. + NONE = "none" + + +class RouteType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """RouteType.""" + + #: The fastest route. + FASTEST = "fastest" + #: The shortest route by distance. + SHORTEST = "shortest" + #: A route balanced by economy and speed. + ECONOMY = "eco" + #: Includes interesting or challenging roads and uses as few motorways as possible. You can choose + #: the level of turns included and also the degree of hilliness. See the hilliness and windingness + #: parameters for how to set this. There is a limit of 900 km on routes planned with + #: ``routeType``\ =thrilling + THRILLING = "thrilling" + + +class SectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """SectionType.""" + + #: Sections of the route that are cars or trains. + CAR_OR_TRAIN = "carTrain" + #: Sections indicating which countries the route is in. + COUNTRY = "country" + #: Sections of the route that are ferries. + FERRY = "ferry" + #: Sections of the route that are motorways. + MOTORWAY = "motorway" + #: Sections of the route that are only suited for pedestrians. + PEDESTRIAN = "pedestrian" + #: Sections of the route that require a toll to be payed. + TOLL_ROAD = "tollRoad" + #: Sections of the route that require a toll vignette to be present. + TOLL_VIGNETTE = "tollVignette" + #: Sections of the route that contain traffic information. + TRAFFIC = "traffic" + #: Sections in relation to the request parameter ``travelMode``. + TRAVEL_MODE = "travelMode" + #: Sections of the route that are tunnels. + TUNNEL = "tunnel" + #: Sections of the route that require use of carpool (HOV/High Occupancy Vehicle) lanes. + CARPOOL = "carpool" + #: Sections of the route that are located within urban areas. + URBAN = "urban" + + +class SimpleCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the incident. Can currently be JAM, ROAD_WORK, ROAD_CLOSURE, or OTHER. See "tec" for + detailed information. + """ + + #: Traffic jam. + JAM = "JAM" + #: Road work. + ROAD_WORK = "ROAD_WORK" + #: Road closure. + ROAD_CLOSURE = "ROAD_CLOSURE" + #: Other. + OTHER = "OTHER" + + +class TravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """TravelMode.""" + + #: The returned routes are optimized for cars. + CAR = "car" + #: The returned routes are optimized for commercial vehicles, like for trucks. + TRUCK = "truck" + #: The returned routes are optimized for taxis. BETA functionality. + TAXI = "taxi" + #: The returned routes are optimized for buses, including the use of bus only lanes. BETA + #: functionality. + BUS = "bus" + #: The returned routes are optimized for vans. BETA functionality. + VAN = "van" + #: The returned routes are optimized for motorcycles. BETA functionality. + MOTORCYCLE = "motorcycle" + #: The returned routes are optimized for bicycles, including use of bicycle lanes. + BICYCLE = "bicycle" + #: The returned routes are optimized for pedestrians, including the use of sidewalks. + PEDESTRIAN = "pedestrian" + + +class VehicleEngineType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """VehicleEngineType.""" + + #: Internal combustion engine. + COMBUSTION = "combustion" + #: Electric engine. + ELECTRIC = "electric" + + +class VehicleLoadType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """VehicleLoadType.""" + + #: Explosives + US_HAZMAT_CLASS1 = "USHazmatClass1" + #: Compressed gas + US_HAZMAT_CLASS2 = "USHazmatClass2" + #: Flammable liquids + US_HAZMAT_CLASS3 = "USHazmatClass3" + #: Flammable solids + US_HAZMAT_CLASS4 = "USHazmatClass4" + #: Oxidizers + US_HAZMAT_CLASS5 = "USHazmatClass5" + #: Poisons + US_HAZMAT_CLASS6 = "USHazmatClass6" + #: Radioactive + US_HAZMAT_CLASS7 = "USHazmatClass7" + #: Corrosives + US_HAZMAT_CLASS8 = "USHazmatClass8" + #: Miscellaneous + US_HAZMAT_CLASS9 = "USHazmatClass9" + #: Explosives + OTHER_HAZMAT_EXPLOSIVE = "otherHazmatExplosive" + #: Miscellaneous + OTHER_HAZMAT_GENERAL = "otherHazmatGeneral" + #: Harmful to water + OTHER_HAZMAT_HARMFUL_TO_WATER = "otherHazmatHarmfulToWater" + + +class WindingnessLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """WindingnessLevel.""" + + #: low + LOW = "low" + #: normal + NORMAL = "normal" + #: high + HIGH = "high" diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_models.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_models.py new file mode 100644 index 000000000000..1d12b83e5710 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_models.py @@ -0,0 +1,2146 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, List, Optional, TYPE_CHECKING, Union + +from .. import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class BatchRequest(_serialization.Model): + """This type represents the request body for the Batch service. + + :ivar batch_items: The list of queries to process. + :vartype batch_items: list[~azure.maps.route.models.BatchRequestItem] + """ + + _attribute_map = { + "batch_items": {"key": "batchItems", "type": "[BatchRequestItem]"}, + } + + def __init__(self, *, batch_items: Optional[List["_models.BatchRequestItem"]] = None, **kwargs): + """ + :keyword batch_items: The list of queries to process. + :paramtype batch_items: list[~azure.maps.route.models.BatchRequestItem] + """ + super().__init__(**kwargs) + self.batch_items = batch_items + + +class BatchRequestItem(_serialization.Model): + """Batch request object. + + :ivar query: This parameter contains a query string used to perform an unstructured geocoding + operation. The query string will be passed verbatim to the search API for processing. + :vartype query: str + """ + + _attribute_map = { + "query": {"key": "query", "type": "str"}, + } + + def __init__(self, *, query: Optional[str] = None, **kwargs): + """ + :keyword query: This parameter contains a query string used to perform an unstructured + geocoding operation. The query string will be passed verbatim to the search API for processing. + :paramtype query: str + """ + super().__init__(**kwargs) + self.query = query + + +class BatchResult(_serialization.Model): + """This object is returned from a successful Batch service call. Extend with 'batchItems' property. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar batch_summary: Summary of the results for the batch request. + :vartype batch_summary: ~azure.maps.route.models.BatchResultSummary + """ + + _validation = { + "batch_summary": {"readonly": True}, + } + + _attribute_map = { + "batch_summary": {"key": "summary", "type": "BatchResultSummary"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.batch_summary = None + + +class BatchResultItem(_serialization.Model): + """An item returned from Batch API. Extend with 'response' property. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status_code: HTTP request status code. + :vartype status_code: int + """ + + _validation = { + "status_code": {"readonly": True}, + } + + _attribute_map = { + "status_code": {"key": "statusCode", "type": "int"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.status_code = None + + +class BatchResultSummary(_serialization.Model): + """Summary of the results for the batch request. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar successful_requests: Number of successful requests in the batch. + :vartype successful_requests: int + :ivar total_requests: Total number of requests in the batch. + :vartype total_requests: int + """ + + _validation = { + "successful_requests": {"readonly": True}, + "total_requests": {"readonly": True}, + } + + _attribute_map = { + "successful_requests": {"key": "successfulRequests", "type": "int"}, + "total_requests": {"key": "totalRequests", "type": "int"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.successful_requests = None + self.total_requests = None + + +class EffectiveSetting(_serialization.Model): + """Effective parameter or data used when calling this Route API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar key: Name of the parameter used. + :vartype key: str + :ivar value: Value of the parameter used. + :vartype value: str + """ + + _validation = { + "key": {"readonly": True}, + "value": {"readonly": True}, + } + + _attribute_map = { + "key": {"key": "key", "type": "str"}, + "value": {"key": "value", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.key = None + self.value = None + + +class ErrorAdditionalInfo(_serialization.Model): + """The resource management error additional info. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: JSON + """ + + _validation = { + "type": {"readonly": True}, + "info": {"readonly": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None + self.info = None + + +class ErrorDetail(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.maps.route.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.maps.route.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetail]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + self.details = None + self.additional_info = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.maps.route.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.maps.route.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class GeoJsonFeatureData(_serialization.Model): + """GeoJsonFeatureData. + + All required parameters must be populated in order to send to Azure. + + :ivar geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `_ for details. Required. + :vartype geometry: ~azure.maps.route.models.GeoJsonGeometry + :ivar properties: Properties can contain any additional metadata about the ``Feature``. Value + can be any JSON object or a JSON null value. + :vartype properties: JSON + :ivar id: Identifier for the feature. + :vartype id: str + :ivar feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :vartype feature_type: str + """ + + _validation = { + "geometry": {"required": True}, + } + + _attribute_map = { + "geometry": {"key": "geometry", "type": "GeoJsonGeometry"}, + "properties": {"key": "properties", "type": "object"}, + "id": {"key": "id", "type": "str"}, + "feature_type": {"key": "featureType", "type": "str"}, + } + + def __init__( + self, + *, + geometry: "_models.GeoJsonGeometry", + properties: Optional[JSON] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + feature_type: Optional[str] = None, + **kwargs + ): + """ + :keyword geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `_ for details. Required. + :paramtype geometry: ~azure.maps.route.models.GeoJsonGeometry + :keyword properties: Properties can contain any additional metadata about the ``Feature``. + Value can be any JSON object or a JSON null value. + :paramtype properties: JSON + :keyword id: Identifier for the feature. + :paramtype id: str + :keyword feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :paramtype feature_type: str + """ + super().__init__(**kwargs) + self.geometry = geometry + self.properties = properties + self.id = id + self.feature_type = feature_type + + +class GeoJsonObject(_serialization.Model): + """A valid ``GeoJSON`` object. Please refer to `RFC 7946 `_ for details. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + GeoJsonFeature, GeoJsonFeatureCollection, GeoJsonGeometry + + All required parameters must be populated in order to send to Azure. + + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + } + + _subtype_map = { + "type": { + "Feature": "GeoJsonFeature", + "FeatureCollection": "GeoJsonFeatureCollection", + "GeoJsonGeometry": "GeoJsonGeometry", + } + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = None # type: Optional[str] + + +class GeoJsonFeature(GeoJsonObject, GeoJsonFeatureData): + """A valid ``GeoJSON Feature`` object type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `_ for details. Required. + :vartype geometry: ~azure.maps.route.models.GeoJsonGeometry + :ivar properties: Properties can contain any additional metadata about the ``Feature``. Value + can be any JSON object or a JSON null value. + :vartype properties: JSON + :ivar id: Identifier for the feature. + :vartype id: str + :ivar feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :vartype feature_type: str + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "geometry": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "geometry": {"key": "geometry", "type": "GeoJsonGeometry"}, + "properties": {"key": "properties", "type": "object"}, + "id": {"key": "id", "type": "str"}, + "feature_type": {"key": "featureType", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + geometry: "_models.GeoJsonGeometry", + properties: Optional[JSON] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + feature_type: Optional[str] = None, + **kwargs + ): + """ + :keyword geometry: A valid ``GeoJSON`` geometry object. The type must be one of the seven valid + GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon + and GeometryCollection. Please refer to `RFC 7946 + `_ for details. Required. + :paramtype geometry: ~azure.maps.route.models.GeoJsonGeometry + :keyword properties: Properties can contain any additional metadata about the ``Feature``. + Value can be any JSON object or a JSON null value. + :paramtype properties: JSON + :keyword id: Identifier for the feature. + :paramtype id: str + :keyword feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :paramtype feature_type: str + """ + super().__init__(geometry=geometry, properties=properties, id=id, feature_type=feature_type, **kwargs) + self.geometry = geometry + self.properties = properties + self.id = id + self.feature_type = feature_type + self.type = "Feature" # type: str + + +class GeoJsonFeatureCollectionData(_serialization.Model): + """GeoJsonFeatureCollectionData. + + All required parameters must be populated in order to send to Azure. + + :ivar features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :vartype features: list[~azure.maps.route.models.GeoJsonFeature] + """ + + _validation = { + "features": {"required": True}, + } + + _attribute_map = { + "features": {"key": "features", "type": "[GeoJsonFeature]"}, + } + + def __init__(self, *, features: List["_models.GeoJsonFeature"], **kwargs): + """ + :keyword features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :paramtype features: list[~azure.maps.route.models.GeoJsonFeature] + """ + super().__init__(**kwargs) + self.features = features + + +class GeoJsonFeatureCollection(GeoJsonObject, GeoJsonFeatureCollectionData): + """A valid ``GeoJSON FeatureCollection`` object type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :vartype features: list[~azure.maps.route.models.GeoJsonFeature] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "features": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "features": {"key": "features", "type": "[GeoJsonFeature]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, features: List["_models.GeoJsonFeature"], **kwargs): + """ + :keyword features: Contains a list of valid ``GeoJSON Feature`` objects. Required. + :paramtype features: list[~azure.maps.route.models.GeoJsonFeature] + """ + super().__init__(features=features, **kwargs) + self.features = features + self.type = "FeatureCollection" # type: str + + +class GeoJsonGeometry(GeoJsonObject): + """A valid ``GeoJSON`` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to `RFC 7946 `_ for details. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + GeoJsonGeometryCollection, GeoJsonLineString, GeoJsonMultiLineString, GeoJsonMultiPoint, + GeoJsonMultiPolygon, GeoJsonPoint, GeoJsonPolygon + + All required parameters must be populated in order to send to Azure. + + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + } + + _subtype_map = { + "type": { + "GeometryCollection": "GeoJsonGeometryCollection", + "LineString": "GeoJsonLineString", + "MultiLineString": "GeoJsonMultiLineString", + "MultiPoint": "GeoJsonMultiPoint", + "MultiPolygon": "GeoJsonMultiPolygon", + "Point": "GeoJsonPoint", + "Polygon": "GeoJsonPolygon", + } + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.type = "GeoJsonGeometry" # type: str + + +class GeoJsonGeometryCollectionData(_serialization.Model): + """GeoJsonGeometryCollectionData. + + All required parameters must be populated in order to send to Azure. + + :ivar geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + """ + + _validation = { + "geometries": {"required": True}, + } + + _attribute_map = { + "geometries": {"key": "geometries", "type": "[GeoJsonGeometry]"}, + } + + def __init__(self, *, geometries: List["_models.GeoJsonGeometry"], **kwargs): + """ + :keyword geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + """ + super().__init__(**kwargs) + self.geometries = geometries + + +class GeoJsonGeometryCollection(GeoJsonGeometry, GeoJsonGeometryCollectionData): + """A valid ``GeoJSON GeometryCollection`` object type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "geometries": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "geometries": {"key": "geometries", "type": "[GeoJsonGeometry]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, geometries: List["_models.GeoJsonGeometry"], **kwargs): + """ + :keyword geometries: Contains a list of valid ``GeoJSON`` geometry objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype geometries: list[~azure.maps.route.models.GeoJsonGeometry] + """ + super().__init__(geometries=geometries, **kwargs) + self.geometries = geometries + self.type = "GeometryCollection" # type: str + + +class GeoJsonLineStringData(_serialization.Model): + """GeoJsonLineStringData. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :vartype coordinates: list[list[float]] + """ + + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + } + + def __init__(self, *, coordinates: List[List[float]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonLineString(GeoJsonGeometry, GeoJsonLineStringData): + """A valid ``GeoJSON LineString`` geometry type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :vartype coordinates: list[list[float]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[float]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson LineString`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = "LineString" # type: str + + +class GeoJsonMultiLineStringData(_serialization.Model): + """GeoJsonMultiLineStringData. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :vartype coordinates: list[list[list[float]]] + """ + + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + } + + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonMultiLineString(GeoJsonGeometry, GeoJsonMultiLineStringData): + """A valid ``GeoJSON MultiLineString`` geometry type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :vartype coordinates: list[list[list[float]]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiLineString`` geometry. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = "MultiLineString" # type: str + + +class GeoJsonMultiPointData(_serialization.Model): + """Data contained by a ``GeoJson MultiPoint``. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :vartype coordinates: list[list[float]] + """ + + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + } + + def __init__(self, *, coordinates: List[List[float]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonMultiPoint(GeoJsonGeometry, GeoJsonMultiPointData): + """A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :vartype coordinates: list[list[float]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[float]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[float]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson MultiPoint`` geometry. Required. + :paramtype coordinates: list[list[float]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = "MultiPoint" # type: str + + +class GeoJsonMultiPolygonData(_serialization.Model): + """GeoJsonMultiPolygonData. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype coordinates: list[list[list[list[float]]]] + """ + + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[[float]]]]"}, + } + + def __init__(self, *, coordinates: List[List[List[List[float]]]], **kwargs): + """ + :keyword coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype coordinates: list[list[list[list[float]]]] + """ + super().__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonMultiPolygon(GeoJsonGeometry, GeoJsonMultiPolygonData): + """A valid ``GeoJSON MultiPolygon`` object type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :vartype coordinates: list[list[list[list[float]]]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[[float]]]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[List[List[float]]]], **kwargs): + """ + :keyword coordinates: Contains a list of valid ``GeoJSON Polygon`` objects. **Note** that + coordinates in GeoJSON are in x, y order (longitude, latitude). Required. + :paramtype coordinates: list[list[list[list[float]]]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = "MultiPolygon" # type: str + + +class GeoJsonPointData(_serialization.Model): + """Data contained by a ``GeoJson Point``. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: A ``Position`` is an array of numbers with two or more elements. The first + two elements are *longitude* and *latitude*\ , precisely in that order. *Altitude/Elevation* is + an optional third element. Please refer to `RFC 7946 + `_ for details. Required. + :vartype coordinates: list[float] + """ + + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[float]"}, + } + + def __init__(self, *, coordinates: List[float], **kwargs): + """ + :keyword coordinates: A ``Position`` is an array of numbers with two or more elements. The + first two elements are *longitude* and *latitude*\ , precisely in that order. + *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 + `_ for details. Required. + :paramtype coordinates: list[float] + """ + super().__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonPoint(GeoJsonGeometry, GeoJsonPointData): + """A valid ``GeoJSON Point`` geometry type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: A ``Position`` is an array of numbers with two or more elements. The first + two elements are *longitude* and *latitude*\ , precisely in that order. *Altitude/Elevation* is + an optional third element. Please refer to `RFC 7946 + `_ for details. Required. + :vartype coordinates: list[float] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[float]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[float], **kwargs): + """ + :keyword coordinates: A ``Position`` is an array of numbers with two or more elements. The + first two elements are *longitude* and *latitude*\ , precisely in that order. + *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 + `_ for details. Required. + :paramtype coordinates: list[float] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = "Point" # type: str + + +class GeoJsonPolygonData(_serialization.Model): + """GeoJsonPolygonData. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :vartype coordinates: list[list[list[float]]] + """ + + _validation = { + "coordinates": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + } + + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonPolygon(GeoJsonGeometry, GeoJsonPolygonData): + """A valid ``GeoJSON Polygon`` geometry type. Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :ivar coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :vartype coordinates: list[list[list[float]]] + :ivar type: Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types + - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, + Feature and FeatureCollection. Required. Known values are: "Point", "MultiPoint", "LineString", + "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", and + "FeatureCollection". + :vartype type: str or ~azure.maps.route.models.GeoJsonObjectType + """ + + _validation = { + "coordinates": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "coordinates": {"key": "coordinates", "type": "[[[float]]]"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, coordinates: List[List[List[float]]], **kwargs): + """ + :keyword coordinates: Coordinates for the ``GeoJson Polygon`` geometry type. Required. + :paramtype coordinates: list[list[list[float]]] + """ + super().__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = "Polygon" # type: str + + +class LatLongPair(_serialization.Model): + """A location represented as a latitude and longitude. + + :ivar latitude: Latitude property. + :vartype latitude: float + :ivar longitude: Longitude property. + :vartype longitude: float + """ + + _attribute_map = { + "latitude": {"key": "latitude", "type": "float"}, + "longitude": {"key": "longitude", "type": "float"}, + } + + def __init__(self, *, latitude: Optional[float] = None, longitude: Optional[float] = None, **kwargs): + """ + :keyword latitude: Latitude property. + :paramtype latitude: float + :keyword longitude: Longitude property. + :paramtype longitude: float + """ + super().__init__(**kwargs) + self.latitude = latitude + self.longitude = longitude + + +class Route(_serialization.Model): + """Route. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object. + :vartype summary: ~azure.maps.route.models.RouteSummary + :ivar legs: Legs array. + :vartype legs: list[~azure.maps.route.models.RouteLeg] + :ivar sections: Sections array. + :vartype sections: list[~azure.maps.route.models.RouteSection] + :ivar guidance: Contains guidance related elements. This field is present only when guidance + was requested and is available. + :vartype guidance: ~azure.maps.route.models.RouteGuidance + """ + + _validation = { + "summary": {"readonly": True}, + "legs": {"readonly": True}, + "sections": {"readonly": True}, + "guidance": {"readonly": True}, + } + + _attribute_map = { + "summary": {"key": "summary", "type": "RouteSummary"}, + "legs": {"key": "legs", "type": "[RouteLeg]"}, + "sections": {"key": "sections", "type": "[RouteSection]"}, + "guidance": {"key": "guidance", "type": "RouteGuidance"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.summary = None + self.legs = None + self.sections = None + self.guidance = None + + +class RouteDirectionParameters(_serialization.Model): + """Post body parameters for Route directions. + + :ivar supporting_points: A GeoJSON Geometry collection representing sequence of coordinates + used as input for route reconstruction and for calculating zero or more alternative routes to + this reference route. + + + * The provided sequence of supporting points is used as input for route reconstruction. + * The alternative routes are calculated between the origin and destination points specified in + the base path parameter locations. + * If both *minDeviationDistance* and *minDeviationTime* are set to zero, then these origin and + destination points are + expected to be at (or very near) the beginning and end of the reference route, respectively. + * Intermediate locations (\ *waypoints*\ ) are not supported when using + :code:`<_supportingPoints_>`. + * The reference route may contain traffic incidents of type _ROAD\ *CLOSURE*\ , which are + ignored for the calculation of the reference route's travel time and traffic delay. + Please refer to `Supporting Points + `_ + for details. + :vartype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection + :ivar avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads + with vignettes in countries not in the list are unaffected. Note: It is an error to specify + both **avoidVignette** and **allowVignette**. + :vartype avoid_vignette: list[str] + :ivar allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying + **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all + countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all + toll roads with vignettes. Note: It is an error to specify both **avoidVignette** and + **allowVignette**. + :vartype allow_vignette: list[str] + :ivar avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only rectangle + polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum number of + avoided areas is **10**. It cannot cross the 180th meridian. It must be between -80 and +80 + degrees of latitude. + :vartype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon + """ + + _attribute_map = { + "supporting_points": {"key": "supportingPoints", "type": "GeoJsonGeometryCollection"}, + "avoid_vignette": {"key": "avoidVignette", "type": "[str]"}, + "allow_vignette": {"key": "allowVignette", "type": "[str]"}, + "avoid_areas": {"key": "avoidAreas", "type": "GeoJsonMultiPolygon"}, + } + + def __init__( + self, + *, + supporting_points: Optional["_models.GeoJsonGeometryCollection"] = None, + avoid_vignette: Optional[List[str]] = None, + allow_vignette: Optional[List[str]] = None, + avoid_areas: Optional["_models.GeoJsonMultiPolygon"] = None, + **kwargs + ): + """ + :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates + used as input for route reconstruction and for calculating zero or more alternative routes to + this reference route. + + + * The provided sequence of supporting points is used as input for route reconstruction. + * The alternative routes are calculated between the origin and destination points specified in + the base path parameter locations. + * If both *minDeviationDistance* and *minDeviationTime* are set to zero, then these origin and + destination points are + expected to be at (or very near) the beginning and end of the reference route, respectively. + * Intermediate locations (\ *waypoints*\ ) are not supported when using + :code:`<_supportingPoints_>`. + * The reference route may contain traffic incidents of type _ROAD\ *CLOSURE*\ , which are + ignored for the calculation of the reference route's travel time and traffic delay. + Please refer to `Supporting Points + `_ + for details. + :paramtype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection + :keyword avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads + with vignettes in countries not in the list are unaffected. Note: It is an error to specify + both **avoidVignette** and **allowVignette**. + :paramtype avoid_vignette: list[str] + :keyword allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying + **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all + countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all + toll roads with vignettes. Note: It is an error to specify both **avoidVignette** and + **allowVignette**. + :paramtype allow_vignette: list[str] + :keyword avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only + rectangle polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum + number of avoided areas is **10**. It cannot cross the 180th meridian. It must be between -80 + and +80 degrees of latitude. + :paramtype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon + """ + super().__init__(**kwargs) + self.supporting_points = supporting_points + self.avoid_vignette = avoid_vignette + self.allow_vignette = allow_vignette + self.avoid_areas = avoid_areas + + +class RouteDirections(_serialization.Model): + """This object is returned from a successful Route Directions call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar routes: Routes array. + :vartype routes: list[~azure.maps.route.models.Route] + :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user + provided waypoint sequence for the original and optimized list. For instance, a response: + + .. code-block:: + + + + + + + + means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the + index starts by 0 the original is "first, second, third" while the optimized is "second, third, + first". + :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] + :ivar report: Reports the effective settings used in the current call. + :vartype report: ~azure.maps.route.models.RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + "routes": {"readonly": True}, + "optimized_waypoints": {"readonly": True}, + } + + _attribute_map = { + "format_version": {"key": "formatVersion", "type": "str"}, + "routes": {"key": "routes", "type": "[Route]"}, + "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__(self, *, report: Optional["_models.RouteReport"] = None, **kwargs): + """ + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(**kwargs) + self.format_version = None + self.routes = None + self.optimized_waypoints = None + self.report = report + + +class RouteDirectionsBatchItem(BatchResultItem): + """An item returned from Route Directions Batch service call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status_code: HTTP request status code. + :vartype status_code: int + :ivar response: The result of the query. RouteDirections if the query completed successfully, + ErrorResponse otherwise. + :vartype response: ~azure.maps.route.models.RouteDirectionsBatchItemResponse + """ + + _validation = { + "status_code": {"readonly": True}, + "response": {"readonly": True}, + } + + _attribute_map = { + "status_code": {"key": "statusCode", "type": "int"}, + "response": {"key": "response", "type": "RouteDirectionsBatchItemResponse"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.response = None + + +class RouteDirectionsBatchItemResponse(RouteDirections, ErrorResponse): + """The result of the query. RouteDirections if the query completed successfully, ErrorResponse otherwise. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: The error object. + :vartype error: ~azure.maps.route.models.ErrorDetail + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar routes: Routes array. + :vartype routes: list[~azure.maps.route.models.Route] + :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user + provided waypoint sequence for the original and optimized list. For instance, a response: + + .. code-block:: + + + + + + + + means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the + index starts by 0 the original is "first, second, third" while the optimized is "second, third, + first". + :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] + :ivar report: Reports the effective settings used in the current call. + :vartype report: ~azure.maps.route.models.RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + "routes": {"readonly": True}, + "optimized_waypoints": {"readonly": True}, + } + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + "format_version": {"key": "formatVersion", "type": "str"}, + "routes": {"key": "routes", "type": "[Route]"}, + "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__( + self, *, error: Optional["_models.ErrorDetail"] = None, report: Optional["_models.RouteReport"] = None, **kwargs + ): + """ + :keyword error: The error object. + :paramtype error: ~azure.maps.route.models.ErrorDetail + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(report=report, error=error, **kwargs) + self.error = error + self.format_version = None + self.routes = None + self.optimized_waypoints = None + self.report = report + + +class RouteDirectionsBatchResult(BatchResult): + """This object is returned from a successful Route Directions Batch service call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar batch_summary: Summary of the results for the batch request. + :vartype batch_summary: ~azure.maps.route.models.BatchResultSummary + :ivar batch_items: Array containing the batch results. + :vartype batch_items: list[~azure.maps.route.models.RouteDirectionsBatchItem] + """ + + _validation = { + "batch_summary": {"readonly": True}, + "batch_items": {"readonly": True}, + } + + _attribute_map = { + "batch_summary": {"key": "summary", "type": "BatchResultSummary"}, + "batch_items": {"key": "batchItems", "type": "[RouteDirectionsBatchItem]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.batch_items = None + + +class RouteGuidance(_serialization.Model): + """Contains guidance related elements. This field is present only when guidance was requested and is available. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar instructions: A list of instructions describing maneuvers. + :vartype instructions: list[~azure.maps.route.models.RouteInstruction] + :ivar instruction_groups: Groups a sequence of instruction elements which are related to each + other. + :vartype instruction_groups: list[~azure.maps.route.models.RouteInstructionGroup] + """ + + _validation = { + "instructions": {"readonly": True}, + "instruction_groups": {"readonly": True}, + } + + _attribute_map = { + "instructions": {"key": "instructions", "type": "[RouteInstruction]"}, + "instruction_groups": {"key": "instructionGroups", "type": "[RouteInstructionGroup]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.instructions = None + self.instruction_groups = None + + +class RouteInstruction(_serialization.Model): # pylint: disable=too-many-instance-attributes + """A set of attributes describing a maneuver, e.g. 'Turn right', 'Keep left', 'Take the ferry', 'Take the motorway', 'Arrive'. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar route_offset_in_meters: Distance from the start of the route to the point of the + instruction. + :vartype route_offset_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time up to the point corresponding to + routeOffsetInMeters. + :vartype travel_time_in_seconds: int + :ivar point: A location represented as a latitude and longitude. + :vartype point: ~azure.maps.route.models.LatLongPair + :ivar point_index: The index of the point in the list of polyline "points" corresponding to the + point of the instruction. + :vartype point_index: int + :ivar instruction_type: Type of the instruction, e.g., turn or change of road form. Known + values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", + and "LOCATION_WAYPOINT". + :vartype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + :ivar road_numbers: The road number(s) of the next significant road segment(s) after the + maneuver, or of the road(s) to be followed. Example: ["E34", "N205"]. + :vartype road_numbers: list[str] + :ivar exit_number: The number(s) of a highway exit taken by the current maneuver. If an exit + has multiple exit numbers, they will be separated by "," and possibly aggregated by "-", e.g., + "10, 13-15". + :vartype exit_number: str + :ivar street: Street name of the next significant road segment after the maneuver, or of the + street that should be followed. + :vartype street: str + :ivar signpost_text: The text on a signpost which is most relevant to the maneuver, or to the + direction that should be followed. + :vartype signpost_text: str + :ivar country_code: 3-character `ISO 3166-1 `_ + alpha-3 country code. E.g. USA. + :vartype country_code: str + :ivar state_code: A subdivision (e.g., state) of the country, represented by the second part of + an `ISO 3166-2 `_ code. This is only available for + some countries like the US, Canada, and Mexico. + :vartype state_code: str + :ivar junction_type: The type of the junction where the maneuver takes place. For larger + roundabouts, two separate instructions are generated for entering and leaving the roundabout. + Known values are: "REGULAR", "ROUNDABOUT", and "BIFURCATION". + :vartype junction_type: str or ~azure.maps.route.models.JunctionType + :ivar turn_angle_in_degrees: Indicates the direction of an instruction. If junctionType + indicates a turn instruction: + + + * 180 = U-turn + * [-179, -1] = Left turn + * 0 = Straight on (a '0 degree' turn) + * [1, 179] = Right turn + + If junctionType indicates a bifurcation instruction: + + + * <0 - keep left + * >0 - keep right. + :vartype turn_angle_in_degrees: int + :ivar roundabout_exit_number: This indicates which exit to take at a roundabout. + :vartype roundabout_exit_number: str + :ivar possible_combine_with_next: It is possible to optionally combine the instruction with the + next one. This can be used to build messages like "Turn left and then turn right". + :vartype possible_combine_with_next: bool + :ivar driving_side: Indicates left-hand vs. right-hand side driving at the point of the + maneuver. Known values are: "LEFT" and "RIGHT". + :vartype driving_side: str or ~azure.maps.route.models.DrivingSide + :ivar maneuver: A code identifying the maneuver. Known values are: "ARRIVE", "ARRIVE_LEFT", + "ARRIVE_RIGHT", "DEPART", "STRAIGHT", "KEEP_RIGHT", "BEAR_RIGHT", "TURN_RIGHT", "SHARP_RIGHT", + "KEEP_LEFT", "BEAR_LEFT", "TURN_LEFT", "SHARP_LEFT", "MAKE_UTURN", "ENTER_MOTORWAY", + "ENTER_FREEWAY", "ENTER_HIGHWAY", "TAKE_EXIT", "MOTORWAY_EXIT_LEFT", "MOTORWAY_EXIT_RIGHT", + "TAKE_FERRY", "ROUNDABOUT_CROSS", "ROUNDABOUT_RIGHT", "ROUNDABOUT_LEFT", "ROUNDABOUT_BACK", + "TRY_MAKE_UTURN", "FOLLOW", "SWITCH_PARALLEL_ROAD", "SWITCH_MAIN_ROAD", "ENTRANCE_RAMP", + "WAYPOINT_LEFT", "WAYPOINT_RIGHT", and "WAYPOINT_REACHED". + :vartype maneuver: str or ~azure.maps.route.models.GuidanceManeuver + :ivar message: A human-readable message for the maneuver. + :vartype message: str + :ivar combined_message: A human-readable message for the maneuver combined with the message + from the next instruction. Sometimes it is possible to combine two successive instructions into + a single instruction making it easier to follow. When this is the case the + possibleCombineWithNext flag will be true. For example: + + .. code-block:: + + 10. Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam + 11. Follow Einsteinweg/A10/E22 towards Ring Amsterdam + + The possibleCombineWithNext flag on instruction 10 is true. This indicates to the clients of + coded guidance that it can be combined with instruction 11. The instructions will be combined + automatically for clients requesting human-readable guidance. The combinedMessage field + contains the combined message: + + .. code-block:: + + Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam + then follow Einsteinweg/A10/E22 towards Ring Amsterdam. + :vartype combined_message: str + """ + + _validation = { + "route_offset_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "point_index": {"readonly": True}, + "road_numbers": {"readonly": True}, + "exit_number": {"readonly": True}, + "street": {"readonly": True}, + "signpost_text": {"readonly": True}, + "country_code": {"readonly": True}, + "state_code": {"readonly": True}, + "junction_type": {"readonly": True}, + "turn_angle_in_degrees": {"readonly": True}, + "roundabout_exit_number": {"readonly": True}, + "possible_combine_with_next": {"readonly": True}, + "driving_side": {"readonly": True}, + "maneuver": {"readonly": True}, + "message": {"readonly": True}, + "combined_message": {"readonly": True}, + } + + _attribute_map = { + "route_offset_in_meters": {"key": "routeOffsetInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "point": {"key": "point", "type": "LatLongPair"}, + "point_index": {"key": "pointIndex", "type": "int"}, + "instruction_type": {"key": "instructionType", "type": "str"}, + "road_numbers": {"key": "roadNumbers", "type": "[str]"}, + "exit_number": {"key": "exitNumber", "type": "str"}, + "street": {"key": "street", "type": "str"}, + "signpost_text": {"key": "signpostText", "type": "str"}, + "country_code": {"key": "countryCode", "type": "str"}, + "state_code": {"key": "stateCode", "type": "str"}, + "junction_type": {"key": "junctionType", "type": "str"}, + "turn_angle_in_degrees": {"key": "turnAngleInDecimalDegrees", "type": "int"}, + "roundabout_exit_number": {"key": "roundaboutExitNumber", "type": "str"}, + "possible_combine_with_next": {"key": "possibleCombineWithNext", "type": "bool"}, + "driving_side": {"key": "drivingSide", "type": "str"}, + "maneuver": {"key": "maneuver", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "combined_message": {"key": "combinedMessage", "type": "str"}, + } + + def __init__( + self, + *, + point: Optional["_models.LatLongPair"] = None, + instruction_type: Optional[Union[str, "_models.GuidanceInstructionType"]] = None, + **kwargs + ): + """ + :keyword point: A location represented as a latitude and longitude. + :paramtype point: ~azure.maps.route.models.LatLongPair + :keyword instruction_type: Type of the instruction, e.g., turn or change of road form. Known + values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", + and "LOCATION_WAYPOINT". + :paramtype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + """ + super().__init__(**kwargs) + self.route_offset_in_meters = None + self.travel_time_in_seconds = None + self.point = point + self.point_index = None + self.instruction_type = instruction_type + self.road_numbers = None + self.exit_number = None + self.street = None + self.signpost_text = None + self.country_code = None + self.state_code = None + self.junction_type = None + self.turn_angle_in_degrees = None + self.roundabout_exit_number = None + self.possible_combine_with_next = None + self.driving_side = None + self.maneuver = None + self.message = None + self.combined_message = None + + +class RouteInstructionGroup(_serialization.Model): + """Groups a sequence of instruction elements which are related to each other. The sequence range is constrained with firstInstructionIndex and lastInstructionIndex. When human-readable text messages are requested for guidance (instructionType=text or tagged), then the instructionGroup has a summary message returned when available. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar first_instruction_index: Index of the first instruction in the instructions and belonging + to this group. + :vartype first_instruction_index: int + :ivar last_instruction_index: Index of the last instruction in the instructions and belonging + to this group. + :vartype last_instruction_index: int + :ivar group_length_in_meters: Length of the group. + :vartype group_length_in_meters: int + :ivar group_message: Summary message when human-readable text messages are requested for + guidance (instructionType=text or tagged). + :vartype group_message: str + """ + + _validation = { + "first_instruction_index": {"readonly": True}, + "last_instruction_index": {"readonly": True}, + "group_length_in_meters": {"readonly": True}, + "group_message": {"readonly": True}, + } + + _attribute_map = { + "first_instruction_index": {"key": "firstInstructionIndex", "type": "int"}, + "last_instruction_index": {"key": "lastInstructionIndex", "type": "int"}, + "group_length_in_meters": {"key": "groupLengthInMeters", "type": "int"}, + "group_message": {"key": "groupMessage", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.first_instruction_index = None + self.last_instruction_index = None + self.group_length_in_meters = None + self.group_message = None + + +class RouteLeg(_serialization.Model): + """A description of a part of a route, comprised of a list of points. Each additional waypoint provided in the request will result in an additional leg in the returned route. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object for route section. + :vartype summary: ~azure.maps.route.models.RouteLegSummary + :ivar points: Points array. + :vartype points: list[~azure.maps.route.models.LatLongPair] + """ + + _validation = { + "summary": {"readonly": True}, + "points": {"readonly": True}, + } + + _attribute_map = { + "summary": {"key": "summary", "type": "RouteLegSummary"}, + "points": {"key": "points", "type": "[LatLongPair]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.summary = None + self.points = None + + +class RouteLegSummary(_serialization.Model): + """Summary object for route section. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar length_in_meters: Length In Meters property. + :vartype length_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time in seconds property that includes the delay + due to real-time traffic. Note that even when traffic=false travelTimeInSeconds still includes + the delay due to traffic. If DepartAt is in the future, travel time is calculated using + time-dependent historic traffic data. + :vartype travel_time_in_seconds: int + :ivar traffic_delay_in_seconds: Estimated delay in seconds caused by the real-time incident(s) + according to traffic information. For routes planned with departure time in the future, delays + is always 0. To return additional travel times using different types of traffic information, + parameter computeTravelTimeFor=all needs to be added. + :vartype traffic_delay_in_seconds: int + :ivar departure_time: The estimated departure time for the route or leg. + :vartype departure_time: ~datetime.datetime + :ivar arrival_time: The estimated arrival time for the route or leg. + :vartype arrival_time: ~datetime.datetime + :ivar no_traffic_travel_time_in_seconds: Estimated travel time calculated as if there are no + delays on the route due to traffic conditions (e.g. congestion). Included only if + computeTravelTimeFor = all is used in the query. + :vartype no_traffic_travel_time_in_seconds: int + :ivar historic_traffic_travel_time_in_seconds: Estimated travel time calculated using + time-dependent historic traffic data. Included only if computeTravelTimeFor = all is used in + the query. + :vartype historic_traffic_travel_time_in_seconds: int + :ivar live_traffic_incidents_travel_time_in_seconds: Estimated travel time calculated using + real-time speed data. Included only if computeTravelTimeFor = all is used in the query. + :vartype live_traffic_incidents_travel_time_in_seconds: int + :ivar fuel_consumption_in_liters: Estimated fuel consumption in liters using the Combustion + Consumption Model. Included if vehicleEngineType is set to *combustion* and + constantSpeedConsumptionInLitersPerHundredkm is specified. The value will be non-negative. + :vartype fuel_consumption_in_liters: float + :ivar battery_consumption_in_kw_h: Estimated electric energy consumption in kilowatt hours + (kWh) using the Electric Consumption Model. Included if vehicleEngineType is set to electric + and constantSpeedConsumptionInkWhPerHundredkm is specified. The value of + batteryConsumptionInkWh includes the recuperated electric energy and can therefore be negative + (which indicates gaining energy). If both maxChargeInkWh and currentChargeInkWh are specified, + recuperation will be capped to ensure that the battery charge level never exceeds + maxChargeInkWh. If neither maxChargeInkWh nor currentChargeInkWh are specified, unconstrained + recuperation is assumed in the consumption calculation. + :vartype battery_consumption_in_kw_h: float + """ + + _validation = { + "length_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "traffic_delay_in_seconds": {"readonly": True}, + "departure_time": {"readonly": True}, + "arrival_time": {"readonly": True}, + "no_traffic_travel_time_in_seconds": {"readonly": True}, + "historic_traffic_travel_time_in_seconds": {"readonly": True}, + "live_traffic_incidents_travel_time_in_seconds": {"readonly": True}, + "fuel_consumption_in_liters": {"readonly": True}, + "battery_consumption_in_kw_h": {"readonly": True}, + } + + _attribute_map = { + "length_in_meters": {"key": "lengthInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "traffic_delay_in_seconds": {"key": "trafficDelayInSeconds", "type": "int"}, + "departure_time": {"key": "departureTime", "type": "iso-8601"}, + "arrival_time": {"key": "arrivalTime", "type": "iso-8601"}, + "no_traffic_travel_time_in_seconds": {"key": "noTrafficTravelTimeInSeconds", "type": "int"}, + "historic_traffic_travel_time_in_seconds": {"key": "historicTrafficTravelTimeInSeconds", "type": "int"}, + "live_traffic_incidents_travel_time_in_seconds": { + "key": "liveTrafficIncidentsTravelTimeInSeconds", + "type": "int", + }, + "fuel_consumption_in_liters": {"key": "fuelConsumptionInLiters", "type": "float"}, + "battery_consumption_in_kw_h": {"key": "batteryConsumptionInkWh", "type": "float"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.length_in_meters = None + self.travel_time_in_seconds = None + self.traffic_delay_in_seconds = None + self.departure_time = None + self.arrival_time = None + self.no_traffic_travel_time_in_seconds = None + self.historic_traffic_travel_time_in_seconds = None + self.live_traffic_incidents_travel_time_in_seconds = None + self.fuel_consumption_in_liters = None + self.battery_consumption_in_kw_h = None + + +class RouteMatrix(_serialization.Model): + """Matrix result object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar status_code: StatusCode property for the current cell in the input matrix. + :vartype status_code: int + :ivar response: Response object of the current cell in the input matrix. + :vartype response: ~azure.maps.route.models.RouteMatrixResultResponse + """ + + _validation = { + "status_code": {"readonly": True}, + "response": {"readonly": True}, + } + + _attribute_map = { + "status_code": {"key": "statusCode", "type": "int"}, + "response": {"key": "response", "type": "RouteMatrixResultResponse"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.status_code = None + self.response = None + + +class RouteMatrixQuery(_serialization.Model): + """An object with a matrix of coordinates. + + :ivar origins: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `_ for details. + :vartype origins: ~azure.maps.route.models.GeoJsonMultiPoint + :ivar destinations: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `_ for details. + :vartype destinations: ~azure.maps.route.models.GeoJsonMultiPoint + """ + + _attribute_map = { + "origins": {"key": "origins", "type": "GeoJsonMultiPoint"}, + "destinations": {"key": "destinations", "type": "GeoJsonMultiPoint"}, + } + + def __init__( + self, + *, + origins: Optional["_models.GeoJsonMultiPoint"] = None, + destinations: Optional["_models.GeoJsonMultiPoint"] = None, + **kwargs + ): + """ + :keyword origins: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `_ for details. + :paramtype origins: ~azure.maps.route.models.GeoJsonMultiPoint + :keyword destinations: A valid ``GeoJSON MultiPoint`` geometry type. Please refer to `RFC 7946 + `_ for details. + :paramtype destinations: ~azure.maps.route.models.GeoJsonMultiPoint + """ + super().__init__(**kwargs) + self.origins = origins + self.destinations = destinations + + +class RouteMatrixResult(_serialization.Model): + """This object is returned from a successful Route Matrix call. For ex, if 2 origins and 3 destinations are provided, there are going to 2 arrays with 3 elements in each. Each element's content depends on the options provided in the query. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar matrix: Results as a 2 dimensional array of route summaries. + :vartype matrix: list[list[~azure.maps.route.models.RouteMatrix]] + :ivar summary: Summary object. + :vartype summary: ~azure.maps.route.models.RouteMatrixSummary + """ + + _validation = { + "format_version": {"readonly": True}, + "matrix": {"readonly": True}, + "summary": {"readonly": True}, + } + + _attribute_map = { + "format_version": {"key": "formatVersion", "type": "str"}, + "matrix": {"key": "matrix", "type": "[[RouteMatrix]]"}, + "summary": {"key": "summary", "type": "RouteMatrixSummary"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.format_version = None + self.matrix = None + self.summary = None + + +class RouteMatrixResultResponse(_serialization.Model): + """Response object of the current cell in the input matrix. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object for route section. + :vartype summary: ~azure.maps.route.models.RouteLegSummary + """ + + _validation = { + "summary": {"readonly": True}, + } + + _attribute_map = { + "summary": {"key": "routeSummary", "type": "RouteLegSummary"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.summary = None + + +class RouteMatrixSummary(_serialization.Model): + """Summary object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar successful_routes: Number of successful routes in the response. + :vartype successful_routes: int + :ivar total_routes: Total number of routes requested. Number of cells in the input matrix. + :vartype total_routes: int + """ + + _validation = { + "successful_routes": {"readonly": True}, + "total_routes": {"readonly": True}, + } + + _attribute_map = { + "successful_routes": {"key": "successfulRoutes", "type": "int"}, + "total_routes": {"key": "totalRoutes", "type": "int"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.successful_routes = None + self.total_routes = None + + +class RouteOptimizedWaypoint(_serialization.Model): + """Optimized way point object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provided_index: Way point index provided by the user. + :vartype provided_index: int + :ivar optimized_index: Optimized way point index from the system. + :vartype optimized_index: int + """ + + _validation = { + "provided_index": {"readonly": True}, + "optimized_index": {"readonly": True}, + } + + _attribute_map = { + "provided_index": {"key": "providedIndex", "type": "int"}, + "optimized_index": {"key": "optimizedIndex", "type": "int"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.provided_index = None + self.optimized_index = None + + +class RouteRange(_serialization.Model): + """Reachable Range. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar center: Center point of the reachable range. + :vartype center: ~azure.maps.route.models.LatLongPair + :ivar boundary: Polygon boundary of the reachable range represented as a list of points. + :vartype boundary: list[~azure.maps.route.models.LatLongPair] + """ + + _validation = { + "boundary": {"readonly": True}, + } + + _attribute_map = { + "center": {"key": "center", "type": "LatLongPair"}, + "boundary": {"key": "boundary", "type": "[LatLongPair]"}, + } + + def __init__(self, *, center: Optional["_models.LatLongPair"] = None, **kwargs): + """ + :keyword center: Center point of the reachable range. + :paramtype center: ~azure.maps.route.models.LatLongPair + """ + super().__init__(**kwargs) + self.center = center + self.boundary = None + + +class RouteRangeResult(_serialization.Model): + """This object is returned from a successful Route Reachable Range call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar reachable_range: Reachable Range. + :vartype reachable_range: ~azure.maps.route.models.RouteRange + :ivar report: Reports the effective settings used in the current call. + :vartype report: ~azure.maps.route.models.RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + } + + _attribute_map = { + "format_version": {"key": "formatVersion", "type": "str"}, + "reachable_range": {"key": "reachableRange", "type": "RouteRange"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__( + self, + *, + reachable_range: Optional["_models.RouteRange"] = None, + report: Optional["_models.RouteReport"] = None, + **kwargs + ): + """ + :keyword reachable_range: Reachable Range. + :paramtype reachable_range: ~azure.maps.route.models.RouteRange + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(**kwargs) + self.format_version = None + self.reachable_range = reachable_range + self.report = report + + +class RouteReport(_serialization.Model): + """Reports the effective settings used in the current call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar effective_settings: Effective parameters or data used when calling this Route API. + :vartype effective_settings: list[~azure.maps.route.models.EffectiveSetting] + """ + + _validation = { + "effective_settings": {"readonly": True}, + } + + _attribute_map = { + "effective_settings": {"key": "effectiveSettings", "type": "[EffectiveSetting]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.effective_settings = None + + +class RouteSection(_serialization.Model): + """Route sections contain additional information about parts of a route. Each section contains at least the elements ``startPointIndex``\ , ``endPointIndex``\ , and ``sectionType``. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar start_point_index: Index of the first point (offset 0) in the route this section applies + to. + :vartype start_point_index: int + :ivar end_point_index: Index of the last point (offset 0) in the route this section applies to. + :vartype end_point_index: int + :ivar section_type: Section types of the reported route response. Known values are: + "CAR_TRAIN", "COUNTRY", "FERRY", "MOTORWAY", "PEDESTRIAN", "TOLL_ROAD", "TOLL_VIGNETTE", + "TRAFFIC", "TRAVEL_MODE", "TUNNEL", "CARPOOL", and "URBAN". + :vartype section_type: str or ~azure.maps.route.models.ResponseSectionType + :ivar travel_mode: Travel mode for the calculated route. The value will be set to ``other`` if + the requested mode of transport is not possible in this section. Known values are: "car", + "truck", "taxi", "bus", "van", "motorcycle", "bicycle", "pedestrian", and "other". + :vartype travel_mode: str or ~azure.maps.route.models.ResponseTravelMode + :ivar simple_category: Type of the incident. Can currently be JAM, ROAD_WORK, ROAD_CLOSURE, or + OTHER. See "tec" for detailed information. Known values are: "JAM", "ROAD_WORK", + "ROAD_CLOSURE", and "OTHER". + :vartype simple_category: str or ~azure.maps.route.models.SimpleCategory + :ivar effective_speed_in_kmh: Effective speed of the incident in km/h, averaged over its entire + length. + :vartype effective_speed_in_kmh: int + :ivar delay_in_seconds: Delay in seconds caused by the incident. + :vartype delay_in_seconds: int + :ivar delay_magnitude: The magnitude of delay caused by the incident. These values correspond + to the values of the response field ty of the `Get Traffic Incident Detail API + `_. Known values + are: "0", "1", "2", "3", and "4". + :vartype delay_magnitude: str or ~azure.maps.route.models.DelayMagnitude + :ivar tec: Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + :vartype tec: ~azure.maps.route.models.RouteSectionTec + """ + + _validation = { + "start_point_index": {"readonly": True}, + "end_point_index": {"readonly": True}, + "section_type": {"readonly": True}, + "travel_mode": {"readonly": True}, + "simple_category": {"readonly": True}, + "effective_speed_in_kmh": {"readonly": True}, + "delay_in_seconds": {"readonly": True}, + "delay_magnitude": {"readonly": True}, + } + + _attribute_map = { + "start_point_index": {"key": "startPointIndex", "type": "int"}, + "end_point_index": {"key": "endPointIndex", "type": "int"}, + "section_type": {"key": "sectionType", "type": "str"}, + "travel_mode": {"key": "travelMode", "type": "str"}, + "simple_category": {"key": "simpleCategory", "type": "str"}, + "effective_speed_in_kmh": {"key": "effectiveSpeedInKmh", "type": "int"}, + "delay_in_seconds": {"key": "delayInSeconds", "type": "int"}, + "delay_magnitude": {"key": "magnitudeOfDelay", "type": "str"}, + "tec": {"key": "tec", "type": "RouteSectionTec"}, + } + + def __init__(self, *, tec: Optional["_models.RouteSectionTec"] = None, **kwargs): + """ + :keyword tec: Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + :paramtype tec: ~azure.maps.route.models.RouteSectionTec + """ + super().__init__(**kwargs) + self.start_point_index = None + self.end_point_index = None + self.section_type = None + self.travel_mode = None + self.simple_category = None + self.effective_speed_in_kmh = None + self.delay_in_seconds = None + self.delay_magnitude = None + self.tec = tec + + +class RouteSectionTec(_serialization.Model): + """Details of the traffic event, using definitions in the `TPEG2-TEC `_ standard. Can contain effectCode and causes elements. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar effect_code: The effect on the traffic flow. Contains a value in the tec001:EffectCode + table, as defined in the `TPEG2-TEC `_ standard. Can + be used to color-code traffic events according to severity. + :vartype effect_code: int + :ivar causes: Causes array. + :vartype causes: list[~azure.maps.route.models.RouteSectionTecCause] + """ + + _validation = { + "effect_code": {"readonly": True}, + } + + _attribute_map = { + "effect_code": {"key": "effectCode", "type": "int"}, + "causes": {"key": "causes", "type": "[RouteSectionTecCause]"}, + } + + def __init__(self, *, causes: Optional[List["_models.RouteSectionTecCause"]] = None, **kwargs): + """ + :keyword causes: Causes array. + :paramtype causes: list[~azure.maps.route.models.RouteSectionTecCause] + """ + super().__init__(**kwargs) + self.effect_code = None + self.causes = causes + + +class RouteSectionTecCause(_serialization.Model): + """The cause of the traffic event. Can contain mainCauseCode and subCauseCode elements. Can be used to define iconography and descriptions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar main_cause_code: The main cause of the traffic event. Contains a value in the + tec002:CauseCode table, as defined in the `TPEG2-TEC + `_ standard. + :vartype main_cause_code: int + :ivar sub_cause_code: The subcause of the traffic event. Contains a value in the sub cause + table defined by the mainCauseCode, as defined in the `TPEG2-TEC + `_ standard. + :vartype sub_cause_code: int + """ + + _validation = { + "main_cause_code": {"readonly": True}, + "sub_cause_code": {"readonly": True}, + } + + _attribute_map = { + "main_cause_code": {"key": "mainCauseCode", "type": "int"}, + "sub_cause_code": {"key": "subCauseCode", "type": "int"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.main_cause_code = None + self.sub_cause_code = None + + +class RouteSummary(_serialization.Model): + """Summary object. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar length_in_meters: Length In Meters property. + :vartype length_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time in seconds property that includes the delay + due to real-time traffic. Note that even when traffic=false travelTimeInSeconds still includes + the delay due to traffic. If DepartAt is in the future, travel time is calculated using + time-dependent historic traffic data. + :vartype travel_time_in_seconds: int + :ivar traffic_delay_in_seconds: Estimated delay in seconds caused by the real-time incident(s) + according to traffic information. For routes planned with departure time in the future, delays + is always 0. To return additional travel times using different types of traffic information, + parameter computeTravelTimeFor=all needs to be added. + :vartype traffic_delay_in_seconds: int + :ivar departure_time: The estimated departure time for the route or leg. + :vartype departure_time: ~datetime.datetime + :ivar arrival_time: The estimated arrival time for the route or leg. + :vartype arrival_time: ~datetime.datetime + """ + + _validation = { + "length_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "traffic_delay_in_seconds": {"readonly": True}, + "departure_time": {"readonly": True}, + "arrival_time": {"readonly": True}, + } + + _attribute_map = { + "length_in_meters": {"key": "lengthInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "traffic_delay_in_seconds": {"key": "trafficDelayInSeconds", "type": "int"}, + "departure_time": {"key": "departureTime", "type": "iso-8601"}, + "arrival_time": {"key": "arrivalTime", "type": "iso-8601"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.length_in_meters = None + self.travel_time_in_seconds = None + self.traffic_delay_in_seconds = None + self.departure_time = None + self.arrival_time = None diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/__init__.py new file mode 100644 index 000000000000..08df5df8aeba --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import RouteOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "RouteOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_operations.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_operations.py new file mode 100644 index 000000000000..8cd8752ec90b --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_operations.py @@ -0,0 +1,6763 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import datetime +from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.polling.base_polling import LROBasePolling +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_route_request_route_matrix_request( + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + client_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/matrix/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if wait_for_results is not None: + _params["waitForResults"] = _SERIALIZER.query("wait_for_results", wait_for_results, "bool") + if compute_travel_time is not None: + _params["computeTravelTimeFor"] = _SERIALIZER.query("compute_travel_time", compute_travel_time, "str") + if filter_section_type is not None: + _params["sectionType"] = _SERIALIZER.query("filter_section_type", filter_section_type, "str") + if arrive_at is not None: + _params["arriveAt"] = _SERIALIZER.query("arrive_at", arrive_at, "iso-8601") + if depart_at is not None: + _params["departAt"] = _SERIALIZER.query("depart_at", depart_at, "iso-8601") + if vehicle_axle_weight is not None: + _params["vehicleAxleWeight"] = _SERIALIZER.query("vehicle_axle_weight", vehicle_axle_weight, "int") + if vehicle_length is not None: + _params["vehicleLength"] = _SERIALIZER.query("vehicle_length", vehicle_length, "float") + if vehicle_height is not None: + _params["vehicleHeight"] = _SERIALIZER.query("vehicle_height", vehicle_height, "float") + if vehicle_width is not None: + _params["vehicleWidth"] = _SERIALIZER.query("vehicle_width", vehicle_width, "float") + if vehicle_max_speed is not None: + _params["vehicleMaxSpeed"] = _SERIALIZER.query("vehicle_max_speed", vehicle_max_speed, "int") + if vehicle_weight is not None: + _params["vehicleWeight"] = _SERIALIZER.query("vehicle_weight", vehicle_weight, "int") + if windingness is not None: + _params["windingness"] = _SERIALIZER.query("windingness", windingness, "str") + if incline_level is not None: + _params["hilliness"] = _SERIALIZER.query("incline_level", incline_level, "str") + if travel_mode is not None: + _params["travelMode"] = _SERIALIZER.query("travel_mode", travel_mode, "str") + if avoid is not None: + _params["avoid"] = [_SERIALIZER.query("avoid", q, "str") if q is not None else "" for q in avoid] + if use_traffic_data is not None: + _params["traffic"] = _SERIALIZER.query("use_traffic_data", use_traffic_data, "bool") + if route_type is not None: + _params["routeType"] = _SERIALIZER.query("route_type", route_type, "str") + if vehicle_load_type is not None: + _params["vehicleLoadType"] = _SERIALIZER.query("vehicle_load_type", vehicle_load_type, "str") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_get_route_matrix_request( + matrix_id: str, *, client_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/matrix/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("matrix_id", matrix_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_request_route_matrix_sync_request( + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + client_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/matrix/sync/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if wait_for_results is not None: + _params["waitForResults"] = _SERIALIZER.query("wait_for_results", wait_for_results, "bool") + if compute_travel_time is not None: + _params["computeTravelTimeFor"] = _SERIALIZER.query("compute_travel_time", compute_travel_time, "str") + if filter_section_type is not None: + _params["sectionType"] = _SERIALIZER.query("filter_section_type", filter_section_type, "str") + if arrive_at is not None: + _params["arriveAt"] = _SERIALIZER.query("arrive_at", arrive_at, "iso-8601") + if depart_at is not None: + _params["departAt"] = _SERIALIZER.query("depart_at", depart_at, "iso-8601") + if vehicle_axle_weight is not None: + _params["vehicleAxleWeight"] = _SERIALIZER.query("vehicle_axle_weight", vehicle_axle_weight, "int") + if vehicle_length is not None: + _params["vehicleLength"] = _SERIALIZER.query("vehicle_length", vehicle_length, "float") + if vehicle_height is not None: + _params["vehicleHeight"] = _SERIALIZER.query("vehicle_height", vehicle_height, "float") + if vehicle_width is not None: + _params["vehicleWidth"] = _SERIALIZER.query("vehicle_width", vehicle_width, "float") + if vehicle_max_speed is not None: + _params["vehicleMaxSpeed"] = _SERIALIZER.query("vehicle_max_speed", vehicle_max_speed, "int") + if vehicle_weight is not None: + _params["vehicleWeight"] = _SERIALIZER.query("vehicle_weight", vehicle_weight, "int") + if windingness is not None: + _params["windingness"] = _SERIALIZER.query("windingness", windingness, "str") + if incline_level is not None: + _params["hilliness"] = _SERIALIZER.query("incline_level", incline_level, "str") + if travel_mode is not None: + _params["travelMode"] = _SERIALIZER.query("travel_mode", travel_mode, "str") + if avoid is not None: + _params["avoid"] = [_SERIALIZER.query("avoid", q, "str") if q is not None else "" for q in avoid] + if use_traffic_data is not None: + _params["traffic"] = _SERIALIZER.query("use_traffic_data", use_traffic_data, "bool") + if route_type is not None: + _params["routeType"] = _SERIALIZER.query("route_type", route_type, "str") + if vehicle_load_type is not None: + _params["vehicleLoadType"] = _SERIALIZER.query("vehicle_load_type", vehicle_load_type, "str") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_get_route_directions_request( + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + vehicle_axle_weight: int = 0, + vehicle_width: float = 0, + vehicle_height: float = 0, + vehicle_length: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + client_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/directions/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["query"] = _SERIALIZER.query("route_points", route_points, "str") + if max_alternatives is not None: + _params["maxAlternatives"] = _SERIALIZER.query( + "max_alternatives", max_alternatives, "int", maximum=5, minimum=0 + ) + if alternative_type is not None: + _params["alternativeType"] = _SERIALIZER.query("alternative_type", alternative_type, "str") + if min_deviation_distance is not None: + _params["minDeviationDistance"] = _SERIALIZER.query("min_deviation_distance", min_deviation_distance, "int") + if arrive_at is not None: + _params["arriveAt"] = _SERIALIZER.query("arrive_at", arrive_at, "iso-8601") + if depart_at is not None: + _params["departAt"] = _SERIALIZER.query("depart_at", depart_at, "iso-8601") + if min_deviation_time is not None: + _params["minDeviationTime"] = _SERIALIZER.query("min_deviation_time", min_deviation_time, "int") + if instructions_type is not None: + _params["instructionsType"] = _SERIALIZER.query("instructions_type", instructions_type, "str") + if language is not None: + _params["language"] = _SERIALIZER.query("language", language, "str") + if compute_best_waypoint_order is not None: + _params["computeBestOrder"] = _SERIALIZER.query( + "compute_best_waypoint_order", compute_best_waypoint_order, "bool" + ) + if route_representation_for_best_order is not None: + _params["routeRepresentation"] = _SERIALIZER.query( + "route_representation_for_best_order", route_representation_for_best_order, "str" + ) + if compute_travel_time is not None: + _params["computeTravelTimeFor"] = _SERIALIZER.query("compute_travel_time", compute_travel_time, "str") + if vehicle_heading is not None: + _params["vehicleHeading"] = _SERIALIZER.query("vehicle_heading", vehicle_heading, "int", maximum=359, minimum=0) + if report is not None: + _params["report"] = _SERIALIZER.query("report", report, "str") + if filter_section_type is not None: + _params["sectionType"] = _SERIALIZER.query("filter_section_type", filter_section_type, "str") + if vehicle_axle_weight is not None: + _params["vehicleAxleWeight"] = _SERIALIZER.query("vehicle_axle_weight", vehicle_axle_weight, "int") + if vehicle_width is not None: + _params["vehicleWidth"] = _SERIALIZER.query("vehicle_width", vehicle_width, "float") + if vehicle_height is not None: + _params["vehicleHeight"] = _SERIALIZER.query("vehicle_height", vehicle_height, "float") + if vehicle_length is not None: + _params["vehicleLength"] = _SERIALIZER.query("vehicle_length", vehicle_length, "float") + if vehicle_max_speed is not None: + _params["vehicleMaxSpeed"] = _SERIALIZER.query("vehicle_max_speed", vehicle_max_speed, "int") + if vehicle_weight is not None: + _params["vehicleWeight"] = _SERIALIZER.query("vehicle_weight", vehicle_weight, "int") + if is_commercial_vehicle is not None: + _params["vehicleCommercial"] = _SERIALIZER.query("is_commercial_vehicle", is_commercial_vehicle, "bool") + if windingness is not None: + _params["windingness"] = _SERIALIZER.query("windingness", windingness, "str") + if incline_level is not None: + _params["hilliness"] = _SERIALIZER.query("incline_level", incline_level, "str") + if travel_mode is not None: + _params["travelMode"] = _SERIALIZER.query("travel_mode", travel_mode, "str") + if avoid is not None: + _params["avoid"] = [_SERIALIZER.query("avoid", q, "str") if q is not None else "" for q in avoid] + if use_traffic_data is not None: + _params["traffic"] = _SERIALIZER.query("use_traffic_data", use_traffic_data, "bool") + if route_type is not None: + _params["routeType"] = _SERIALIZER.query("route_type", route_type, "str") + if vehicle_load_type is not None: + _params["vehicleLoadType"] = _SERIALIZER.query("vehicle_load_type", vehicle_load_type, "str") + if vehicle_engine_type is not None: + _params["vehicleEngineType"] = _SERIALIZER.query("vehicle_engine_type", vehicle_engine_type, "str") + if constant_speed_consumption_in_liters_per_hundred_km is not None: + _params["constantSpeedConsumptionInLitersPerHundredkm"] = _SERIALIZER.query( + "constant_speed_consumption_in_liters_per_hundred_km", + constant_speed_consumption_in_liters_per_hundred_km, + "str", + ) + if current_fuel_in_liters is not None: + _params["currentFuelInLiters"] = _SERIALIZER.query("current_fuel_in_liters", current_fuel_in_liters, "float") + if auxiliary_power_in_liters_per_hour is not None: + _params["auxiliaryPowerInLitersPerHour"] = _SERIALIZER.query( + "auxiliary_power_in_liters_per_hour", auxiliary_power_in_liters_per_hour, "float" + ) + if fuel_energy_density_in_megajoules_per_liter is not None: + _params["fuelEnergyDensityInMJoulesPerLiter"] = _SERIALIZER.query( + "fuel_energy_density_in_megajoules_per_liter", fuel_energy_density_in_megajoules_per_liter, "float" + ) + if acceleration_efficiency is not None: + _params["accelerationEfficiency"] = _SERIALIZER.query( + "acceleration_efficiency", acceleration_efficiency, "float", maximum=1, minimum=0 + ) + if deceleration_efficiency is not None: + _params["decelerationEfficiency"] = _SERIALIZER.query( + "deceleration_efficiency", deceleration_efficiency, "float", maximum=1, minimum=0 + ) + if uphill_efficiency is not None: + _params["uphillEfficiency"] = _SERIALIZER.query( + "uphill_efficiency", uphill_efficiency, "float", maximum=1, minimum=0 + ) + if downhill_efficiency is not None: + _params["downhillEfficiency"] = _SERIALIZER.query( + "downhill_efficiency", downhill_efficiency, "float", maximum=1, minimum=0 + ) + if constant_speed_consumption_in_kw_h_per_hundred_km is not None: + _params["constantSpeedConsumptionInkWhPerHundredkm"] = _SERIALIZER.query( + "constant_speed_consumption_in_kw_h_per_hundred_km", + constant_speed_consumption_in_kw_h_per_hundred_km, + "str", + ) + if current_charge_in_kw_h is not None: + _params["currentChargeInkWh"] = _SERIALIZER.query("current_charge_in_kw_h", current_charge_in_kw_h, "float") + if max_charge_in_kw_h is not None: + _params["maxChargeInkWh"] = _SERIALIZER.query("max_charge_in_kw_h", max_charge_in_kw_h, "float") + if auxiliary_power_in_kw is not None: + _params["auxiliaryPowerInkW"] = _SERIALIZER.query("auxiliary_power_in_kw", auxiliary_power_in_kw, "float") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_get_route_directions_with_additional_parameters_request( + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + client_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/directions/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["query"] = _SERIALIZER.query("route_points", route_points, "str") + if max_alternatives is not None: + _params["maxAlternatives"] = _SERIALIZER.query( + "max_alternatives", max_alternatives, "int", maximum=5, minimum=0 + ) + if alternative_type is not None: + _params["alternativeType"] = _SERIALIZER.query("alternative_type", alternative_type, "str") + if min_deviation_distance is not None: + _params["minDeviationDistance"] = _SERIALIZER.query("min_deviation_distance", min_deviation_distance, "int") + if min_deviation_time is not None: + _params["minDeviationTime"] = _SERIALIZER.query("min_deviation_time", min_deviation_time, "int") + if instructions_type is not None: + _params["instructionsType"] = _SERIALIZER.query("instructions_type", instructions_type, "str") + if language is not None: + _params["language"] = _SERIALIZER.query("language", language, "str") + if compute_best_waypoint_order is not None: + _params["computeBestOrder"] = _SERIALIZER.query( + "compute_best_waypoint_order", compute_best_waypoint_order, "bool" + ) + if route_representation_for_best_order is not None: + _params["routeRepresentation"] = _SERIALIZER.query( + "route_representation_for_best_order", route_representation_for_best_order, "str" + ) + if compute_travel_time is not None: + _params["computeTravelTimeFor"] = _SERIALIZER.query("compute_travel_time", compute_travel_time, "str") + if vehicle_heading is not None: + _params["vehicleHeading"] = _SERIALIZER.query("vehicle_heading", vehicle_heading, "int", maximum=359, minimum=0) + if report is not None: + _params["report"] = _SERIALIZER.query("report", report, "str") + if filter_section_type is not None: + _params["sectionType"] = _SERIALIZER.query("filter_section_type", filter_section_type, "str") + if arrive_at is not None: + _params["arriveAt"] = _SERIALIZER.query("arrive_at", arrive_at, "iso-8601") + if depart_at is not None: + _params["departAt"] = _SERIALIZER.query("depart_at", depart_at, "iso-8601") + if vehicle_axle_weight is not None: + _params["vehicleAxleWeight"] = _SERIALIZER.query("vehicle_axle_weight", vehicle_axle_weight, "int") + if vehicle_length is not None: + _params["vehicleLength"] = _SERIALIZER.query("vehicle_length", vehicle_length, "float") + if vehicle_height is not None: + _params["vehicleHeight"] = _SERIALIZER.query("vehicle_height", vehicle_height, "float") + if vehicle_width is not None: + _params["vehicleWidth"] = _SERIALIZER.query("vehicle_width", vehicle_width, "float") + if vehicle_max_speed is not None: + _params["vehicleMaxSpeed"] = _SERIALIZER.query("vehicle_max_speed", vehicle_max_speed, "int") + if vehicle_weight is not None: + _params["vehicleWeight"] = _SERIALIZER.query("vehicle_weight", vehicle_weight, "int") + if is_commercial_vehicle is not None: + _params["vehicleCommercial"] = _SERIALIZER.query("is_commercial_vehicle", is_commercial_vehicle, "bool") + if windingness is not None: + _params["windingness"] = _SERIALIZER.query("windingness", windingness, "str") + if incline_level is not None: + _params["hilliness"] = _SERIALIZER.query("incline_level", incline_level, "str") + if travel_mode is not None: + _params["travelMode"] = _SERIALIZER.query("travel_mode", travel_mode, "str") + if avoid is not None: + _params["avoid"] = [_SERIALIZER.query("avoid", q, "str") if q is not None else "" for q in avoid] + if use_traffic_data is not None: + _params["traffic"] = _SERIALIZER.query("use_traffic_data", use_traffic_data, "bool") + if route_type is not None: + _params["routeType"] = _SERIALIZER.query("route_type", route_type, "str") + if vehicle_load_type is not None: + _params["vehicleLoadType"] = _SERIALIZER.query("vehicle_load_type", vehicle_load_type, "str") + if vehicle_engine_type is not None: + _params["vehicleEngineType"] = _SERIALIZER.query("vehicle_engine_type", vehicle_engine_type, "str") + if constant_speed_consumption_in_liters_per_hundred_km is not None: + _params["constantSpeedConsumptionInLitersPerHundredkm"] = _SERIALIZER.query( + "constant_speed_consumption_in_liters_per_hundred_km", + constant_speed_consumption_in_liters_per_hundred_km, + "str", + ) + if current_fuel_in_liters is not None: + _params["currentFuelInLiters"] = _SERIALIZER.query("current_fuel_in_liters", current_fuel_in_liters, "float") + if auxiliary_power_in_liters_per_hour is not None: + _params["auxiliaryPowerInLitersPerHour"] = _SERIALIZER.query( + "auxiliary_power_in_liters_per_hour", auxiliary_power_in_liters_per_hour, "float" + ) + if fuel_energy_density_in_megajoules_per_liter is not None: + _params["fuelEnergyDensityInMJoulesPerLiter"] = _SERIALIZER.query( + "fuel_energy_density_in_megajoules_per_liter", fuel_energy_density_in_megajoules_per_liter, "float" + ) + if acceleration_efficiency is not None: + _params["accelerationEfficiency"] = _SERIALIZER.query( + "acceleration_efficiency", acceleration_efficiency, "float", maximum=1, minimum=0 + ) + if deceleration_efficiency is not None: + _params["decelerationEfficiency"] = _SERIALIZER.query( + "deceleration_efficiency", deceleration_efficiency, "float", maximum=1, minimum=0 + ) + if uphill_efficiency is not None: + _params["uphillEfficiency"] = _SERIALIZER.query( + "uphill_efficiency", uphill_efficiency, "float", maximum=1, minimum=0 + ) + if downhill_efficiency is not None: + _params["downhillEfficiency"] = _SERIALIZER.query( + "downhill_efficiency", downhill_efficiency, "float", maximum=1, minimum=0 + ) + if constant_speed_consumption_in_kw_h_per_hundred_km is not None: + _params["constantSpeedConsumptionInkWhPerHundredkm"] = _SERIALIZER.query( + "constant_speed_consumption_in_kw_h_per_hundred_km", + constant_speed_consumption_in_kw_h_per_hundred_km, + "str", + ) + if current_charge_in_kw_h is not None: + _params["currentChargeInkWh"] = _SERIALIZER.query("current_charge_in_kw_h", current_charge_in_kw_h, "float") + if max_charge_in_kw_h is not None: + _params["maxChargeInkWh"] = _SERIALIZER.query("max_charge_in_kw_h", max_charge_in_kw_h, "float") + if auxiliary_power_in_kw is not None: + _params["auxiliaryPowerInkW"] = _SERIALIZER.query("auxiliary_power_in_kw", auxiliary_power_in_kw, "float") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_get_route_range_request( + format: Union[str, _models.ResponseFormat] = "json", + *, + query: List[float], + fuel_budget_in_liters: Optional[float] = None, + energy_budget_in_kw_h: Optional[float] = None, + time_budget_in_sec: Optional[float] = None, + distance_budget_in_meters: Optional[float] = None, + depart_at: Optional[datetime.datetime] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + use_traffic_data: Optional[bool] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + vehicle_axle_weight: int = 0, + vehicle_width: float = 0, + vehicle_height: float = 0, + vehicle_length: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + client_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/range/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["query"] = _SERIALIZER.query("query", query, "[float]", div=",") + if fuel_budget_in_liters is not None: + _params["fuelBudgetInLiters"] = _SERIALIZER.query("fuel_budget_in_liters", fuel_budget_in_liters, "float") + if energy_budget_in_kw_h is not None: + _params["energyBudgetInkWh"] = _SERIALIZER.query("energy_budget_in_kw_h", energy_budget_in_kw_h, "float") + if time_budget_in_sec is not None: + _params["timeBudgetInSec"] = _SERIALIZER.query("time_budget_in_sec", time_budget_in_sec, "float") + if distance_budget_in_meters is not None: + _params["distanceBudgetInMeters"] = _SERIALIZER.query( + "distance_budget_in_meters", distance_budget_in_meters, "float" + ) + if depart_at is not None: + _params["departAt"] = _SERIALIZER.query("depart_at", depart_at, "iso-8601") + if route_type is not None: + _params["routeType"] = _SERIALIZER.query("route_type", route_type, "str") + if use_traffic_data is not None: + _params["traffic"] = _SERIALIZER.query("use_traffic_data", use_traffic_data, "bool") + if avoid is not None: + _params["avoid"] = [_SERIALIZER.query("avoid", q, "str") if q is not None else "" for q in avoid] + if travel_mode is not None: + _params["travelMode"] = _SERIALIZER.query("travel_mode", travel_mode, "str") + if incline_level is not None: + _params["hilliness"] = _SERIALIZER.query("incline_level", incline_level, "str") + if windingness is not None: + _params["windingness"] = _SERIALIZER.query("windingness", windingness, "str") + if vehicle_axle_weight is not None: + _params["vehicleAxleWeight"] = _SERIALIZER.query("vehicle_axle_weight", vehicle_axle_weight, "int") + if vehicle_width is not None: + _params["vehicleWidth"] = _SERIALIZER.query("vehicle_width", vehicle_width, "float") + if vehicle_height is not None: + _params["vehicleHeight"] = _SERIALIZER.query("vehicle_height", vehicle_height, "float") + if vehicle_length is not None: + _params["vehicleLength"] = _SERIALIZER.query("vehicle_length", vehicle_length, "float") + if vehicle_max_speed is not None: + _params["vehicleMaxSpeed"] = _SERIALIZER.query("vehicle_max_speed", vehicle_max_speed, "int") + if vehicle_weight is not None: + _params["vehicleWeight"] = _SERIALIZER.query("vehicle_weight", vehicle_weight, "int") + if is_commercial_vehicle is not None: + _params["vehicleCommercial"] = _SERIALIZER.query("is_commercial_vehicle", is_commercial_vehicle, "bool") + if vehicle_load_type is not None: + _params["vehicleLoadType"] = _SERIALIZER.query("vehicle_load_type", vehicle_load_type, "str") + if vehicle_engine_type is not None: + _params["vehicleEngineType"] = _SERIALIZER.query("vehicle_engine_type", vehicle_engine_type, "str") + if constant_speed_consumption_in_liters_per_hundred_km is not None: + _params["constantSpeedConsumptionInLitersPerHundredkm"] = _SERIALIZER.query( + "constant_speed_consumption_in_liters_per_hundred_km", + constant_speed_consumption_in_liters_per_hundred_km, + "str", + ) + if current_fuel_in_liters is not None: + _params["currentFuelInLiters"] = _SERIALIZER.query("current_fuel_in_liters", current_fuel_in_liters, "float") + if auxiliary_power_in_liters_per_hour is not None: + _params["auxiliaryPowerInLitersPerHour"] = _SERIALIZER.query( + "auxiliary_power_in_liters_per_hour", auxiliary_power_in_liters_per_hour, "float" + ) + if fuel_energy_density_in_megajoules_per_liter is not None: + _params["fuelEnergyDensityInMJoulesPerLiter"] = _SERIALIZER.query( + "fuel_energy_density_in_megajoules_per_liter", fuel_energy_density_in_megajoules_per_liter, "float" + ) + if acceleration_efficiency is not None: + _params["accelerationEfficiency"] = _SERIALIZER.query( + "acceleration_efficiency", acceleration_efficiency, "float", maximum=1, minimum=0 + ) + if deceleration_efficiency is not None: + _params["decelerationEfficiency"] = _SERIALIZER.query( + "deceleration_efficiency", deceleration_efficiency, "float", maximum=1, minimum=0 + ) + if uphill_efficiency is not None: + _params["uphillEfficiency"] = _SERIALIZER.query( + "uphill_efficiency", uphill_efficiency, "float", maximum=1, minimum=0 + ) + if downhill_efficiency is not None: + _params["downhillEfficiency"] = _SERIALIZER.query( + "downhill_efficiency", downhill_efficiency, "float", maximum=1, minimum=0 + ) + if constant_speed_consumption_in_kw_h_per_hundred_km is not None: + _params["constantSpeedConsumptionInkWhPerHundredkm"] = _SERIALIZER.query( + "constant_speed_consumption_in_kw_h_per_hundred_km", + constant_speed_consumption_in_kw_h_per_hundred_km, + "str", + ) + if current_charge_in_kw_h is not None: + _params["currentChargeInkWh"] = _SERIALIZER.query("current_charge_in_kw_h", current_charge_in_kw_h, "float") + if max_charge_in_kw_h is not None: + _params["maxChargeInkWh"] = _SERIALIZER.query("max_charge_in_kw_h", max_charge_in_kw_h, "float") + if auxiliary_power_in_kw is not None: + _params["auxiliaryPowerInkW"] = _SERIALIZER.query("auxiliary_power_in_kw", auxiliary_power_in_kw, "float") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_request_route_directions_batch_request( + format: Union[str, _models.JsonFormat] = "json", *, client_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/directions/batch/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_get_route_directions_batch_request( + batch_id: str, *, client_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/directions/batch/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("batch_id", batch_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_route_request_route_directions_batch_sync_request( + format: Union[str, _models.JsonFormat] = "json", *, client_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "1.0")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/route/directions/batch/sync/{format}" + path_format_arguments = { + "format": _SERIALIZER.url("format", format, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if client_id is not None: + _headers["x-ms-client-id"] = _SERIALIZER.header("client_id", client_id, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class RouteOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.maps.route.MapsRouteClient`'s + :attr:`route` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _request_route_matrix_initial( + self, + route_matrix_query: Union[_models.RouteMatrixQuery, IO], + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + **kwargs: Any + ) -> Optional[_models.RouteMatrixResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_matrix_query, (IO, bytes)): + _content = route_matrix_query + else: + _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") + + request = build_route_request_route_matrix_request( + format=format, + wait_for_results=wait_for_results, + compute_travel_time=compute_travel_time, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @overload + def begin_request_route_matrix( + self, + route_matrix_query: _models.RouteMatrixQuery, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_request_route_matrix( + self, + route_matrix_query: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_request_route_matrix( + self, + route_matrix_query: Union[_models.RouteMatrixQuery, IO], + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + **kwargs: Any + ) -> LROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Is either a model type or a IO type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._request_route_matrix_initial( # type: ignore + route_matrix_query=route_matrix_query, + format=format, + wait_for_results=wait_for_results, + compute_travel_time=compute_travel_time, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + def _get_route_matrix_initial(self, matrix_id: str, **kwargs: Any) -> Optional[_models.RouteMatrixResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteMatrixResult]] + + request = build_route_get_route_matrix_request( + matrix_id=matrix_id, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace + def begin_get_route_matrix(self, matrix_id: str, **kwargs: Any) -> LROPoller[_models.RouteMatrixResult]: + """**Applies to**\ : see pricing `tiers `_. + + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param matrix_id: Matrix id received after the Matrix Route request was accepted successfully. + Required. + :type matrix_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._get_route_matrix_initial( # type: ignore + matrix_id=matrix_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + @overload + def request_route_matrix_sync( + self, + route_matrix_query: _models.RouteMatrixQuery, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteMatrixResult: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def request_route_matrix_sync( + self, + route_matrix_query: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteMatrixResult: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :type route_matrix_query: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def request_route_matrix_sync( + self, + route_matrix_query: Union[_models.RouteMatrixQuery, IO], + format: Union[str, _models.JsonFormat] = "json", + *, + wait_for_results: Optional[bool] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + **kwargs: Any + ) -> _models.RouteMatrixResult: + """**Applies to**\ : see pricing `tiers `_. + + The Matrix Routing service allows calculation of a matrix of route summaries for a set of + routes defined by origin and destination locations by using an asynchronous (async) or + synchronous (sync) POST request. For every given origin, the service calculates the cost of + routing from that origin to every given destination. The set of origins and the set of + destinations can be thought of as the column and row headers of a table and each cell in the + table contains the costs of routing from the origin to the destination for that cell. As an + example, let's say a food delivery company has 20 drivers and they need to find the closest + driver to pick up the delivery from the restaurant. To solve this use case, they can call + Matrix Route API. + + For each route, the travel times and distances are returned. You can use the computed costs to + determine which detailed routes to calculate using the Route Directions API. + + The maximum size of a matrix for async request is **700** and for sync request it's **100** + (the number of origins multiplied by the number of destinations). + + Submit Synchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + If your scenario requires synchronous requests and the maximum size of the matrix is less than + or equal to 100, you might want to make synchronous request. The maximum size of a matrix for + this API is **100** (the number of origins multiplied by the number of destinations). With that + constraint in mind, examples of possible matrix dimensions are: 10x10, 6x8, 9x8 (it does not + need to be square). + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/sync/json?api-version=1.0&subscription-key={subscription-key} + + Submit Asynchronous Route Matrix Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex routing + requests. When you make a request by using async request, by default the service returns a 202 + response code along a redirect URL in the Location field of the response header. This URL + should be checked periodically until the response data or error information is available. If + ``waitForResults`` parameter in the request is set to true, user will get a 200 response if the + request is finished under 120 seconds. + + The maximum size of a matrix for this API is **700** (the number of origins multiplied by the + number of destinations). With that constraint in mind, examples of possible matrix dimensions + are: 50x10, 10x10, 28x25. 10x70 (it does not need to be square). + + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/matrix/json?api-version=1.0&subscription-key={subscription-key} + + Here's a typical sequence of asynchronous operations: + + + #. + Client sends a Route Matrix POST request to Azure Maps + + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Route Matrix request has been accepted. + + HTTP ``Error`` - There was an error processing your Route Matrix request. This could + either be a 400 Bad Request or any other Error status code. + + + + #. + If the Matrix Route request was accepted successfully, the Location header in the response + contains the URL to download the results of the request. This status URI looks like the + following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + + #. Client issues a GET request on the download URL obtained in Step 3 to download the results + + Download Sync Results + ^^^^^^^^^^^^^^^^^^^^^ + + When you make a POST request for Route Matrix Sync API, the service returns 200 response code + for successful request and a response array. The response body will contain the data and there + will be no possibility to retrieve the results later. + + Download Async Results + ^^^^^^^^^^^^^^^^^^^^^^ + + When a request issues a ``202 Accepted`` response, the request is being processed using our + async pipeline. You will be given a URL to check the progress of your async request in the + location header of the response. This status URI looks like the following: + + .. code-block:: + + GET + https://atlas.microsoft.com/route/matrix/{matrixId}?api-version=1.0?subscription-key={subscription-key} + + The URL provided by the location header will return the following responses when a ``GET`` + request is issued. + + .. + + HTTP ``202 Accepted`` - Matrix request was accepted but is still being processed. Please try + again in some time. + + HTTP ``200 OK`` - Matrix request successfully processed. The response body contains all of + the results. + + :param route_matrix_query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Is either a model type or a IO type. Required. + :type route_matrix_query: ~azure.maps.route.models.RouteMatrixQuery or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + 408: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteMatrixResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_matrix_query, (IO, bytes)): + _content = route_matrix_query + else: + _json = self._serialize.body(route_matrix_query, "RouteMatrixQuery") + + request = build_route_request_route_matrix_sync_request( + format=format, + wait_for_results=wait_for_results, + compute_travel_time=compute_travel_time, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteMatrixResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + @distributed_trace + def get_route_directions( + self, + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + vehicle_axle_weight: int = 0, + vehicle_width: float = 0, + vehicle_height: float = 0, + vehicle_length: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. + Proper nouns (the names of streets, plazas, etc.) are returned in the specified language, or + if that is not available, they are returned in an available language that is close to it. + Allowed values are (a subset of) the IETF language tags. The currently supported languages are + listed in the `Supported languages section + `_. + + Default value: en-GB. Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + + request = build_route_get_route_directions_request( + format=format, + route_points=route_points, + max_alternatives=max_alternatives, + alternative_type=alternative_type, + min_deviation_distance=min_deviation_distance, + arrive_at=arrive_at, + depart_at=depart_at, + min_deviation_time=min_deviation_time, + instructions_type=instructions_type, + language=language, + compute_best_waypoint_order=compute_best_waypoint_order, + route_representation_for_best_order=route_representation_for_best_order, + compute_travel_time=compute_travel_time, + vehicle_heading=vehicle_heading, + report=report, + filter_section_type=filter_section_type, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_width=vehicle_width, + vehicle_height=vehicle_height, + vehicle_length=vehicle_length, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + is_commercial_vehicle=is_commercial_vehicle, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + vehicle_engine_type=vehicle_engine_type, + constant_speed_consumption_in_liters_per_hundred_km=constant_speed_consumption_in_liters_per_hundred_km, + current_fuel_in_liters=current_fuel_in_liters, + auxiliary_power_in_liters_per_hour=auxiliary_power_in_liters_per_hour, + fuel_energy_density_in_megajoules_per_liter=fuel_energy_density_in_megajoules_per_liter, + acceleration_efficiency=acceleration_efficiency, + deceleration_efficiency=deceleration_efficiency, + uphill_efficiency=uphill_efficiency, + downhill_efficiency=downhill_efficiency, + constant_speed_consumption_in_kw_h_per_hundred_km=constant_speed_consumption_in_kw_h_per_hundred_km, + current_charge_in_kw_h=current_charge_in_kw_h, + max_charge_in_kw_h=max_charge_in_kw_h, + auxiliary_power_in_kw=auxiliary_power_in_kw, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteDirections", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + @overload + def get_route_directions_with_additional_parameters( + self, + route_direction_parameters: _models.RouteDirectionParameters, + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of a vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param route_direction_parameters: Used for reconstructing a route and for calculating zero or + more alternative routes to this reference route. The provided sequence of coordinates is used + as input for route reconstruction. The alternative routes are calculated between the origin + and destination points specified in the base path parameter locations. If both + minDeviationDistance and minDeviationTime are set to zero, then these origin and destination + points are expected to be at (or very near) the beginning and end of the reference route, + respectively. Intermediate locations (waypoints) are not supported when using + supportingPoints. + + Setting at least one of minDeviationDistance or minDeviationTime to a value greater than zero + has the following consequences: + + + * The origin point of the calculateRoute request must be on (or very near) the input reference + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. + * The values of minDeviationDistance and minDeviationTime determine how far alternative routes + will be guaranteed to follow the reference route from the origin point onwards. + * The route must use departAt. + * The vehicleHeading is ignored. Required. + :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def get_route_directions_with_additional_parameters( + self, + route_direction_parameters: IO, + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of a vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param route_direction_parameters: Used for reconstructing a route and for calculating zero or + more alternative routes to this reference route. The provided sequence of coordinates is used + as input for route reconstruction. The alternative routes are calculated between the origin + and destination points specified in the base path parameter locations. If both + minDeviationDistance and minDeviationTime are set to zero, then these origin and destination + points are expected to be at (or very near) the beginning and end of the reference route, + respectively. Intermediate locations (waypoints) are not supported when using + supportingPoints. + + Setting at least one of minDeviationDistance or minDeviationTime to a value greater than zero + has the following consequences: + + + * The origin point of the calculateRoute request must be on (or very near) the input reference + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. + * The values of minDeviationDistance and minDeviationTime determine how far alternative routes + will be guaranteed to follow the reference route from the origin point onwards. + * The route must use departAt. + * The vehicleHeading is ignored. Required. + :type route_direction_parameters: IO + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def get_route_directions_with_additional_parameters( + self, + route_direction_parameters: Union[_models.RouteDirectionParameters, IO], + format: Union[str, _models.ResponseFormat] = "json", + *, + route_points: str, + max_alternatives: Optional[int] = None, + alternative_type: Optional[Union[str, _models.AlternativeRouteType]] = None, + min_deviation_distance: Optional[int] = None, + min_deviation_time: Optional[int] = None, + instructions_type: Optional[Union[str, _models.RouteInstructionsType]] = None, + language: Optional[str] = None, + compute_best_waypoint_order: Optional[bool] = None, + route_representation_for_best_order: Optional[Union[str, _models.RouteRepresentationForBestOrder]] = None, + compute_travel_time: Optional[Union[str, _models.ComputeTravelTime]] = None, + vehicle_heading: Optional[int] = None, + report: Optional[Union[str, _models.Report]] = None, + filter_section_type: Optional[Union[str, _models.SectionType]] = None, + arrive_at: Optional[datetime.datetime] = None, + depart_at: Optional[datetime.datetime] = None, + vehicle_axle_weight: int = 0, + vehicle_length: float = 0, + vehicle_height: float = 0, + vehicle_width: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + use_traffic_data: Optional[bool] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + **kwargs: Any + ) -> _models.RouteDirections: + """**Applies to**\ : see pricing `tiers `_. + + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + Routing service provides a set of parameters for a detailed description of a vehicle-specific + Consumption Model. Please check `Consumption Model + `_ for detailed explanation of + the concepts and parameters involved. + + :param route_direction_parameters: Used for reconstructing a route and for calculating zero or + more alternative routes to this reference route. The provided sequence of coordinates is used + as input for route reconstruction. The alternative routes are calculated between the origin + and destination points specified in the base path parameter locations. If both + minDeviationDistance and minDeviationTime are set to zero, then these origin and destination + points are expected to be at (or very near) the beginning and end of the reference route, + respectively. Intermediate locations (waypoints) are not supported when using + supportingPoints. + + Setting at least one of minDeviationDistance or minDeviationTime to a value greater than zero + has the following consequences: + + + * The origin point of the calculateRoute request must be on (or very near) the input reference + route. If this is not the case, an error is returned. However, the origin point does not need + to be at the beginning of the input reference route (it can be thought of as the current + vehicle position on the reference route). + * The reference route, returned as the first route in the calculateRoute response, will start + at the origin point specified in the calculateRoute request. The initial part of the input + reference route up until the origin point will be excluded from the response. + * The values of minDeviationDistance and minDeviationTime determine how far alternative routes + will be guaranteed to follow the reference route from the origin point onwards. + * The route must use departAt. + * The vehicleHeading is ignored. Is either a model type or a IO type. Required. + :type route_direction_parameters: ~azure.maps.route.models.RouteDirectionParameters or IO + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword route_points: The Coordinates through which the route is calculated, delimited by a + colon. A minimum of two coordinates is required. The first one is the origin and the last is + the destination of the route. Optional coordinates in-between act as WayPoints in the route. + You can pass up to 150 WayPoints. Required. + :paramtype route_points: str + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. Setting + )minDeviationTime_ to a value greater than zero has the following consequences: + + + * The origin point of the *calculateRoute* Request must be on + (or very near) the input reference route. + + * If this is not the case, an error is returned. + * However, the origin point does not need to be at the beginning + of the input reference route (it can be thought of as the current + vehicle position on the reference route). + + * The reference route, returned as the first route in the *calculateRoute* + Response, will start at the origin point specified in the *calculateRoute* + Request. The initial part of the input reference route up until the origin + point will be excluded from the Response. + * The values of *minDeviationDistance* and *minDeviationTime* determine + how far alternative routes will be guaranteed to follow the reference + route from the origin point onwards. + * The route must use *departAt*. + * The *vehicleHeading* is ignored. Default value is None. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirections] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_direction_parameters, (IO, bytes)): + _content = route_direction_parameters + else: + _json = self._serialize.body(route_direction_parameters, "RouteDirectionParameters") + + request = build_route_get_route_directions_with_additional_parameters_request( + format=format, + route_points=route_points, + max_alternatives=max_alternatives, + alternative_type=alternative_type, + min_deviation_distance=min_deviation_distance, + min_deviation_time=min_deviation_time, + instructions_type=instructions_type, + language=language, + compute_best_waypoint_order=compute_best_waypoint_order, + route_representation_for_best_order=route_representation_for_best_order, + compute_travel_time=compute_travel_time, + vehicle_heading=vehicle_heading, + report=report, + filter_section_type=filter_section_type, + arrive_at=arrive_at, + depart_at=depart_at, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_length=vehicle_length, + vehicle_height=vehicle_height, + vehicle_width=vehicle_width, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + is_commercial_vehicle=is_commercial_vehicle, + windingness=windingness, + incline_level=incline_level, + travel_mode=travel_mode, + avoid=avoid, + use_traffic_data=use_traffic_data, + route_type=route_type, + vehicle_load_type=vehicle_load_type, + vehicle_engine_type=vehicle_engine_type, + constant_speed_consumption_in_liters_per_hundred_km=constant_speed_consumption_in_liters_per_hundred_km, + current_fuel_in_liters=current_fuel_in_liters, + auxiliary_power_in_liters_per_hour=auxiliary_power_in_liters_per_hour, + fuel_energy_density_in_megajoules_per_liter=fuel_energy_density_in_megajoules_per_liter, + acceleration_efficiency=acceleration_efficiency, + deceleration_efficiency=deceleration_efficiency, + uphill_efficiency=uphill_efficiency, + downhill_efficiency=downhill_efficiency, + constant_speed_consumption_in_kw_h_per_hundred_km=constant_speed_consumption_in_kw_h_per_hundred_km, + current_charge_in_kw_h=current_charge_in_kw_h, + max_charge_in_kw_h=max_charge_in_kw_h, + auxiliary_power_in_kw=auxiliary_power_in_kw, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteDirections", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + @distributed_trace + def get_route_range( + self, + format: Union[str, _models.ResponseFormat] = "json", + *, + query: List[float], + fuel_budget_in_liters: Optional[float] = None, + energy_budget_in_kw_h: Optional[float] = None, + time_budget_in_sec: Optional[float] = None, + distance_budget_in_meters: Optional[float] = None, + depart_at: Optional[datetime.datetime] = None, + route_type: Optional[Union[str, _models.RouteType]] = None, + use_traffic_data: Optional[bool] = None, + avoid: Optional[List[Union[str, _models.RouteAvoidType]]] = None, + travel_mode: Optional[Union[str, _models.TravelMode]] = None, + incline_level: Optional[Union[str, _models.InclineLevel]] = None, + windingness: Optional[Union[str, _models.WindingnessLevel]] = None, + vehicle_axle_weight: int = 0, + vehicle_width: float = 0, + vehicle_height: float = 0, + vehicle_length: float = 0, + vehicle_max_speed: int = 0, + vehicle_weight: int = 0, + is_commercial_vehicle: bool = False, + vehicle_load_type: Optional[Union[str, _models.VehicleLoadType]] = None, + vehicle_engine_type: Optional[Union[str, _models.VehicleEngineType]] = None, + constant_speed_consumption_in_liters_per_hundred_km: Optional[str] = None, + current_fuel_in_liters: Optional[float] = None, + auxiliary_power_in_liters_per_hour: Optional[float] = None, + fuel_energy_density_in_megajoules_per_liter: Optional[float] = None, + acceleration_efficiency: Optional[float] = None, + deceleration_efficiency: Optional[float] = None, + uphill_efficiency: Optional[float] = None, + downhill_efficiency: Optional[float] = None, + constant_speed_consumption_in_kw_h_per_hundred_km: Optional[str] = None, + current_charge_in_kw_h: Optional[float] = None, + max_charge_in_kw_h: Optional[float] = None, + auxiliary_power_in_kw: Optional[float] = None, + **kwargs: Any + ) -> _models.RouteRangeResult: + """**Route Range (Isochrone) API** + + **Applies to**\ : see pricing `tiers `_. + + This service will calculate a set of locations that can be reached from the origin point based + on fuel, energy, time or distance budget that is specified. A polygon boundary (or Isochrone) + is returned in a counterclockwise orientation as well as the precise polygon center which was + the result of the origin point. + + The returned polygon can be used for further processing such as `Search Inside Geometry + `_ to search for + POIs within the provided Isochrone. + + :param format: Desired format of the response. Value can be either *json* or *xml*. Known + values are: "json" and "xml". Default value is "json". + :type format: str or ~azure.maps.route.models.ResponseFormat + :keyword query: The Coordinate from which the range calculation should start. Required. + :paramtype query: list[float] + :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can + be travelled using the specified Combustion Consumption Model.:code:`
` When + fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption + Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype fuel_budget_in_liters: float + :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines + maximal range which can be travelled using the specified Electric Consumption + Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype energy_budget_in_kw_h: float + :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be + travelled using driving time. The Consumption Model will only affect the range when routeType + is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype time_budget_in_sec: float + :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range + which can be travelled using driving distance. The Consumption Model will only affect the + range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype distance_budget_in_meters: float + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword use_traffic_data: Possible values: + + + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored + during routing, the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``\ =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + + + * + A value of 0 means that an appropriate value for the vehicle will be determined and applied + during route planning. + + * + A non-zero value may be overridden during route planning. For example, the current traffic + flow is 60 km/hour. If the vehicle maximum speed is set to 50 km/hour, the routing engine will + consider 60 km/hour as this is the current situation. If the maximum speed of the vehicle is + provided as 80 km/hour but the current traffic flow is 60 km/hour, then routing engine will + again use 60 km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + + + * + It is mandatory if any of the *Efficiency parameters are set. + + * + It must be strictly positive when used in the context of the Consumption Model. Weight + restrictions are considered. + + * + If no detailed **Consumption Model** is specified and the value of **vehicleWeight** is + non-zero, then weight restrictions are considered. + + * + In all other cases, this parameter is ignored. + + Sensible Values : for **Combustion Model** : 1600, for **Electric Model** : 1900. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of colon-delimited speed & consumption-rate pairs. The list + defines points on a consumption curve. Consumption rates for speeds not in the list are found + as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in l/100km) is between 0.01 and 100000.0. + + Sensible Values : 50,6.3:130,11.5 + + **Note** : This parameter is required for **The Combustion Consumption Model**. Default value + is None. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + + Sensible Values : 55. Default value is None. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 0.2. Default value is None. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. For + example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel. + + This parameter is required if any ***Efficiency** parameter is set. + + Sensible Values : 34.2. Default value is None. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **decelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **decelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.33, for **Electric Model** : 0.66. Default + value is None. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **accelerationEfficiency**. + + The range of values allowed are 0.0 to 1/\ **accelerationEfficiency**. + + Sensible Values : for **Combustion Model** : 0.83, for **Electric Model** : 0.91. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **downhillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **downhillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.27, for **Electric Model** : 0.74. Default + value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + + Must be paired with **uphillEfficiency**. + + The range of values allowed are 0.0 to 1/\ **uphillEfficiency**. + + Sensible Values : for **Combustion Model** : 0.51, for **Electric Model** : 0.73. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + + Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a + consumption curve. Consumption rates for speeds not in the list are found as follows: + + + * + by linear interpolation, if the given speed lies in between two speeds in the list + + * + by linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by + the nearest two points in the list + + The list must contain between 1 and 25 points (inclusive), and may not contain duplicate + points for the same speed. If it only contains a single point, then the consumption rate of + that point is used without further processing. + + Consumption specified for the largest speed must be greater than or equal to that of the + penultimate largest speed. This ensures that extrapolation does not lead to negative + consumption rates. + + Similarly, consumption values specified for the two smallest speeds in the list cannot lead to + a negative consumption rate for any smaller speed. + + The valid range for the consumption values(expressed in kWh/100km) is between 0.01 and + 100000.0. + + Sensible Values : 50,8.2:130,21.3 + + This parameter is required for **Electric consumption model**. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + + This parameter co-exists with **maxChargeInkWh** parameter. + + The range of values allowed are 0.0 to **maxChargeInkWh**. + + Sensible Values : 43. Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + + This parameter co-exists with **currentChargeInkWh** parameter. + + Minimum value has to be greater than or equal to **currentChargeInkWh**. + + Sensible Values : 85. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + + It can be used to specify consumption due to devices and systems such as AC systems, radio, + heating, etc. + + Sensible Values : 1.7. Default value is None. + :paramtype auxiliary_power_in_kw: float + :return: RouteRangeResult + :rtype: ~azure.maps.route.models.RouteRangeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteRangeResult] + + request = build_route_get_route_range_request( + format=format, + query=query, + fuel_budget_in_liters=fuel_budget_in_liters, + energy_budget_in_kw_h=energy_budget_in_kw_h, + time_budget_in_sec=time_budget_in_sec, + distance_budget_in_meters=distance_budget_in_meters, + depart_at=depart_at, + route_type=route_type, + use_traffic_data=use_traffic_data, + avoid=avoid, + travel_mode=travel_mode, + incline_level=incline_level, + windingness=windingness, + vehicle_axle_weight=vehicle_axle_weight, + vehicle_width=vehicle_width, + vehicle_height=vehicle_height, + vehicle_length=vehicle_length, + vehicle_max_speed=vehicle_max_speed, + vehicle_weight=vehicle_weight, + is_commercial_vehicle=is_commercial_vehicle, + vehicle_load_type=vehicle_load_type, + vehicle_engine_type=vehicle_engine_type, + constant_speed_consumption_in_liters_per_hundred_km=constant_speed_consumption_in_liters_per_hundred_km, + current_fuel_in_liters=current_fuel_in_liters, + auxiliary_power_in_liters_per_hour=auxiliary_power_in_liters_per_hour, + fuel_energy_density_in_megajoules_per_liter=fuel_energy_density_in_megajoules_per_liter, + acceleration_efficiency=acceleration_efficiency, + deceleration_efficiency=deceleration_efficiency, + uphill_efficiency=uphill_efficiency, + downhill_efficiency=downhill_efficiency, + constant_speed_consumption_in_kw_h_per_hundred_km=constant_speed_consumption_in_kw_h_per_hundred_km, + current_charge_in_kw_h=current_charge_in_kw_h, + max_charge_in_kw_h=max_charge_in_kw_h, + auxiliary_power_in_kw=auxiliary_power_in_kw, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteRangeResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + def _request_route_directions_batch_initial( + self, + route_directions_batch_queries: Union[_models.BatchRequest, IO], + format: Union[str, _models.JsonFormat] = "json", + **kwargs: Any + ) -> Optional[_models.RouteDirectionsBatchResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_directions_batch_queries, (IO, bytes)): + _content = route_directions_batch_queries + else: + _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") + + request = build_route_request_route_directions_batch_request( + format=format, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @overload + def begin_request_route_directions_batch( + self, + route_directions_batch_queries: _models.BatchRequest, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RouteDirectionsBatchResult]: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Asynchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex route + requests + + + * It allows the retrieval of results in a separate call (multiple downloads are possible). + * The asynchronous API is optimized for reliability and is not expected to run into a timeout. + * The number of batch items is limited to **700** for this API. + + When you make a request by using async request, by default the service returns a 202 response + code along a redirect URL in the Location field of the response header. This URL should be + checked periodically until the response data or error information is available. + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + Please note that asynchronous batch request is a long-running request. Here's a typical + sequence of operations: + + + #. Client sends a Route Directions Batch ``POST`` request to Azure Maps + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request has been accepted. + + HTTP ``Error`` - There was an error processing your Batch request. This could either be a + ``400 Bad Request`` or any other ``Error`` status code. + + + #. + If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: + + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\ ) to the *status URI* before running it. :code:`
` + + + #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the + batch results. + + POST Body for Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To send the *route directions* queries you will use a ``POST`` request where the request body + will contain the ``batchItems`` array in ``json`` format and the ``Content-Type`` header will + be set to ``application/json``. Here's a sample request body containing 3 *route directions* + queries: + + .. code-block:: json + + { + "batchItems": [ + { "query": + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, + { "query": + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } + ] + } + + A *route directions* query in a batch is just a partial URL *without* the protocol, base URL, + path, api-version and subscription-key. It can accept any of the supported *route directions* + `URI parameters + `_. The + string values in the *route directions* query must be properly escaped (e.g. " character should + be escaped with ) and it should also be properly URL-encoded. + + The async API allows caller to batch up to **700** queries and sync API up to **100** queries, + and the batch should contain at least **1** query. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_request_route_directions_batch( + self, + route_directions_batch_queries: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RouteDirectionsBatchResult]: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Asynchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex route + requests + + + * It allows the retrieval of results in a separate call (multiple downloads are possible). + * The asynchronous API is optimized for reliability and is not expected to run into a timeout. + * The number of batch items is limited to **700** for this API. + + When you make a request by using async request, by default the service returns a 202 response + code along a redirect URL in the Location field of the response header. This URL should be + checked periodically until the response data or error information is available. + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + Please note that asynchronous batch request is a long-running request. Here's a typical + sequence of operations: + + + #. Client sends a Route Directions Batch ``POST`` request to Azure Maps + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request has been accepted. + + HTTP ``Error`` - There was an error processing your Batch request. This could either be a + ``400 Bad Request`` or any other ``Error`` status code. + + + #. + If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: + + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\ ) to the *status URI* before running it. :code:`
` + + + #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the + batch results. + + POST Body for Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To send the *route directions* queries you will use a ``POST`` request where the request body + will contain the ``batchItems`` array in ``json`` format and the ``Content-Type`` header will + be set to ``application/json``. Here's a sample request body containing 3 *route directions* + queries: + + .. code-block:: json + + { + "batchItems": [ + { "query": + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, + { "query": + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } + ] + } + + A *route directions* query in a batch is just a partial URL *without* the protocol, base URL, + path, api-version and subscription-key. It can accept any of the supported *route directions* + `URI parameters + `_. The + string values in the *route directions* query must be properly escaped (e.g. " character should + be escaped with ) and it should also be properly URL-encoded. + + The async API allows caller to batch up to **700** queries and sync API up to **100** queries, + and the batch should contain at least **1** query. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_request_route_directions_batch( + self, + route_directions_batch_queries: Union[_models.BatchRequest, IO], + format: Union[str, _models.JsonFormat] = "json", + **kwargs: Any + ) -> LROPoller[_models.RouteDirectionsBatchResult]: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Asynchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Asynchronous API is appropriate for processing big volumes of relatively complex route + requests + + + * It allows the retrieval of results in a separate call (multiple downloads are possible). + * The asynchronous API is optimized for reliability and is not expected to run into a timeout. + * The number of batch items is limited to **700** for this API. + + When you make a request by using async request, by default the service returns a 202 response + code along a redirect URL in the Location field of the response header. This URL should be + checked periodically until the response data or error information is available. + The asynchronous responses are stored for **14** days. The redirect URL returns a 404 response + if used after the expiration period. + + Please note that asynchronous batch request is a long-running request. Here's a typical + sequence of operations: + + + #. Client sends a Route Directions Batch ``POST`` request to Azure Maps + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request has been accepted. + + HTTP ``Error`` - There was an error processing your Batch request. This could either be a + ``400 Bad Request`` or any other ``Error`` status code. + + + #. + If the batch request was accepted successfully, the ``Location`` header in the response + contains the URL to download the results of the batch request. + This status URI looks like following: + + ``GET https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0`` + Note:- Please remember to add AUTH information (subscription-key/azure_auth - See `Security + <#security>`_\ ) to the *status URI* before running it. :code:`
` + + + #. Client issues a ``GET`` request on the *download URL* obtained in Step 3 to download the + batch results. + + POST Body for Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To send the *route directions* queries you will use a ``POST`` request where the request body + will contain the ``batchItems`` array in ``json`` format and the ``Content-Type`` header will + be set to ``application/json``. Here's a sample request body containing 3 *route directions* + queries: + + .. code-block:: json + + { + "batchItems": [ + { "query": + "?query=47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + }, + { "query": + "?query=40.759856,-73.985108:40.771136,-73.973506&travelMode=pedestrian&routeType=shortest" }, + { "query": "?query=48.923159,-122.557362:32.621279,-116.840362" } + ] + } + + A *route directions* query in a batch is just a partial URL *without* the protocol, base URL, + path, api-version and subscription-key. It can accept any of the supported *route directions* + `URI parameters + `_. The + string values in the *route directions* query must be properly escaped (e.g. " character should + be escaped with ) and it should also be properly URL-encoded. + + The async API allows caller to batch up to **700** queries and sync API up to **100** queries, + and the batch should contain at least **1** query. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Is either a model type or a IO type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._request_route_directions_batch_initial( # type: ignore + route_directions_batch_queries=route_directions_batch_queries, + format=format, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + def _get_route_directions_batch_initial( + self, batch_id: str, **kwargs: Any + ) -> Optional[_models.RouteDirectionsBatchResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.RouteDirectionsBatchResult]] + + request = build_route_get_route_directions_batch_request( + batch_id=batch_id, + client_id=self._config.client_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + @distributed_trace + def begin_get_route_directions_batch( + self, batch_id: str, **kwargs: Any + ) -> LROPoller[_models.RouteDirectionsBatchResult]: + """**Applies to**\ : see pricing `tiers `_. + + Download Asynchronous Batch Results + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + To download the async batch results you will issue a ``GET`` request to the batch download + endpoint. This *download URL* can be obtained from the ``Location`` header of a successful + ``POST`` batch request and looks like the following: + + .. code-block:: + + https://atlas.microsoft.com/route/directions/batch/{batch-id}?api-version=1.0&subscription-key={subscription-key} + + Here's the typical sequence of operations for downloading the batch results: + + + #. Client sends a ``GET`` request using the *download URL*. + #. + The server will respond with one of the following: + + .. + + HTTP ``202 Accepted`` - Batch request was accepted but is still being processed. Please + try again in some time. + + HTTP ``200 OK`` - Batch request successfully processed. The response body contains all + the batch results. + + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param batch_id: Batch id for querying the operation. Required. + :type batch_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._get_route_directions_batch_initial( # type: ignore + batch_id=batch_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, LROBasePolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + @overload + def request_route_directions_batch_sync( + self, + route_directions_batch_queries: _models.BatchRequest, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirectionsBatchResult: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Synchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Synchronous API is recommended for lightweight batch requests. When the service receives a + request, it will respond as soon as the batch items are calculated and there will be no + possibility to retrieve the results later. The Synchronous API will return a timeout error (a + 408 response) if the request takes longer than 60 seconds. The number of batch items is limited + to **100** for this API. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirectionsBatchResult + :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def request_route_directions_batch_sync( + self, + route_directions_batch_queries: IO, + format: Union[str, _models.JsonFormat] = "json", + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RouteDirectionsBatchResult: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Synchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Synchronous API is recommended for lightweight batch requests. When the service receives a + request, it will respond as soon as the batch items are calculated and there will be no + possibility to retrieve the results later. The Synchronous API will return a timeout error (a + 408 response) if the request takes longer than 60 seconds. The number of batch items is limited + to **100** for this API. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type route_directions_batch_queries: IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RouteDirectionsBatchResult + :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def request_route_directions_batch_sync( + self, + route_directions_batch_queries: Union[_models.BatchRequest, IO], + format: Union[str, _models.JsonFormat] = "json", + **kwargs: Any + ) -> _models.RouteDirectionsBatchResult: + """**Route Directions Batch API** + + **Applies to**\ : see pricing `tiers `_. + + The Route Directions Batch API sends batches of queries to `Route Directions API + `_ using just a single API + call. You can call Route Directions Batch API to run either asynchronously (async) or + synchronously (sync). The async API allows caller to batch up to **700** queries and sync API + up to **100** queries. + + Submit Synchronous Batch Request + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The Synchronous API is recommended for lightweight batch requests. When the service receives a + request, it will respond as soon as the batch items are calculated and there will be no + possibility to retrieve the results later. The Synchronous API will return a timeout error (a + 408 response) if the request takes longer than 60 seconds. The number of batch items is limited + to **100** for this API. + + .. code-block:: + + POST + https://atlas.microsoft.com/route/directions/batch/sync/json?api-version=1.0&subscription-key={subscription-key} + + Batch Response Model + ^^^^^^^^^^^^^^^^^^^^ + + The returned data content is similar for async and sync requests. When downloading the results + of an async batch request, if the batch has finished processing, the response body contains the + batch response. This batch response contains a ``summary`` component that indicates the + ``totalRequests`` that were part of the original batch request and ``successfulRequests``\ i.e. + queries which were executed successfully. The batch response also includes a ``batchItems`` + array which contains a response for each and every query in the batch request. The + ``batchItems`` will contain the results in the exact same order the original queries were sent + in the batch request. Each item in ``batchItems`` contains ``statusCode`` and ``response`` + fields. Each ``response`` in ``batchItems`` is of one of the following types: + + + * + `\ ``RouteDirections`` + `_ - If the + query completed successfully. + + * + ``Error`` - If the query failed. The response will contain a ``code`` and a ``message`` in + this case. + + Here's a sample Batch Response with 1 *successful* and 1 *failed* result: + + .. code-block:: json + + { + "summary": { + "successfulRequests": 1, + "totalRequests": 2 + }, + "batchItems": [ + { + "statusCode": 200, + "response": { + "routes": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1758, + "travelTimeInSeconds": 387, + "trafficDelayInSeconds": 0, + "departureTime": "2018-07-17T00:49:56+00:00", + "arrivalTime": "2018-07-17T00:56:22+00:00" + }, + "points": [ + { + "latitude": 47.62094, + "longitude": -122.34892 + }, + { + "latitude": 47.62094, + "longitude": -122.3485 + }, + { + "latitude": 47.62095, + "longitude": -122.3476 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 40, + "sectionType": "TRAVEL_MODE", + "travelMode": "bicycle" + } + ] + } + ] + } + }, + { + "statusCode": 400, + "response": + { + "error": + { + "code": "400 BadRequest", + "message": "Bad request: one or more parameters were incorrectly + specified or are mutually exclusive." + } + } + } + ] + }. + + :param route_directions_batch_queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Is either a model type or a IO type. Required. + :type route_directions_batch_queries: ~azure.maps.route.models.BatchRequest or IO + :param format: Desired format of the response. Only ``json`` format is supported. "json" + Default value is "json". + :type format: str or ~azure.maps.route.models.JsonFormat + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: RouteDirectionsBatchResult + :rtype: ~azure.maps.route.models.RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + 408: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.ErrorResponse, response) + ), + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RouteDirectionsBatchResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(route_directions_batch_queries, (IO, bytes)): + _content = route_directions_batch_queries + else: + _json = self._serialize.body(route_directions_batch_queries, "BatchRequest") + + request = build_route_request_route_directions_batch_sync_request( + format=format, + client_id=self._config.client_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("RouteDirectionsBatchResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_patch.py b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_generated/py.typed b/sdk/maps/azure-maps-route/azure/maps/route/_generated/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_generated/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_route_client.py b/sdk/maps/azure-maps-route/azure/maps/route/_route_client.py new file mode 100644 index 000000000000..78d2b5e7816f --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_route_client.py @@ -0,0 +1,836 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# pylint: disable=unused-import,ungrouped-imports, R0904, C0302, W0212 +from typing import Union, Any, List, Tuple, overload +from azure.core.tracing.decorator import distributed_trace +from azure.core.credentials import AzureKeyCredential, TokenCredential +from azure.core.polling import LROPoller +from ._base_client import MapsRouteClientBase +from .models import ( + RouteDirectionsBatchResult, + RouteDirections, + RouteRangeResult, + RouteMatrixResult, + RouteMatrixQuery, + LatLon, + TravelMode +) + +from ._generated.models import ( + ResponseFormat +) + +def get_batch_id_from_poller(polling_method): + if hasattr(polling_method, "_operation"): + operation=polling_method._operation + return operation._location_url.split('/')[-1].split('?')[0] + return None + +# By default, use the latest supported API version +class MapsRouteClient(MapsRouteClientBase): + """Azure Maps Route REST APIs. + + :param credential: + Credential needed for the client to connect to Azure. + :type credential: + ~azure.core.credentials.TokenCredential or ~azure.core.credentials.AzureKeyCredential + :keyword str base_url: + Supported Maps Services or Language resource base_url + (protocol and hostname, for example: 'https://us.atlas.microsoft.com'). + :keyword str client_id: + Specifies which account is intended for usage with the Azure AD security model. + It represents a unique ID for the Azure Maps account. + :keyword api_version: + The API version of the service to use for requests. It defaults to the latest service version. + Setting to an older version may result in reduced feature compatibility. + :paramtype api_version: str + """ + + def __init__( + self, + credential: Union[AzureKeyCredential, TokenCredential], + **kwargs: Any + )-> None: + + super().__init__( + credential=credential, **kwargs + ) + + # cSpell:disable + @distributed_trace + def get_route_directions( + self, + route_points: Union[List[LatLon], List[Tuple]], + **kwargs: Any + ) -> RouteDirections: + """ + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + :param route_points: The Coordinate from which the range calculation should start, coordinates as (lat, lon) + :type route_points: List[LatLon] or List[Tuple] + :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates + used as input for route reconstruction and for calculating zero or more alternative routes to + this reference route. + :paramtype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection + :keyword avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads + with vignettes in countries not in the list are unaffected. + :paramtype avoid_vignette: list[str] + :keyword allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying + **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all + countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all + toll roads with vignettes. + :paramtype allow_vignette: list[str] + :keyword avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only rectangle + polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum number of + avoided areas is **10**. + :paramtype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + :paramtype auxiliary_power_in_kw: float + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + query_items="" + route_directions_body={} + if route_points: + query_items = ":".join([(str(route_point[0])+","+str(route_point[1])) for route_point in route_points]) + + supporting_points = kwargs.pop('supporting_points', None) + avoid_vignette = kwargs.pop('avoid_vignette', None) + allow_vignette = kwargs.pop('allow_vignette', None) + avoid_areas = kwargs.pop('avoid_areas', None) + if supporting_points or avoid_vignette or allow_vignette or avoid_areas is not None: + route_directions_body['supporting_points'] = supporting_points + route_directions_body['avoid_vignette'] = avoid_vignette + route_directions_body['allow_vignette'] = allow_vignette + route_directions_body['avoid_areas'] = avoid_areas + + if route_directions_body: + # import pdb; pdb.set_trace() + return self._route_client.get_route_directions_with_additional_parameters( + format=ResponseFormat.JSON, + route_direction_parameters=route_directions_body, + route_points=query_items, + **kwargs + ) + return self._route_client.get_route_directions( + format=ResponseFormat.JSON, + route_points=query_items, + **kwargs + ) + + # cSpell:disable + @distributed_trace + def get_route_range( + self, + coordinates: Union[LatLon, Tuple], + **kwargs: Any + ) -> RouteRangeResult: + + """**Route Range (Isochrone) API** + + This service will calculate a set of locations that can be reached from the origin point based + on fuel, energy, time or distance budget that is specified. A polygon boundary (or Isochrone) + is returned in a counterclockwise orientation as well as the precise polygon center which was + the result of the origin point. + + :param coordinates: The Coordinate from which the range calculation should start, coordinates as (lat, lon) + :type coordinates: LatLon or Tuple + :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can + be travelled using the specified Combustion Consumption Model.:code:`
` When + fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption + Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype fuel_budget_in_liters: float + :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines + maximal range which can be travelled using the specified Electric Consumption + Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype energy_budget_in_kw_h: float + :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be + travelled using driving time. The Consumption Model will only affect the range when routeType + is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype time_budget_in_sec: float + :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range + which can be travelled using driving distance. The Consumption Model will only affect the + range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype distance_budget_in_meters: float + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. + :paramtype use_traffic_data: bool + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + Default value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). Default value is None. + :paramtype auxiliary_power_in_kw: float + :return: RouteRangeResult + :rtype: ~azure.maps.route.models.RouteRangeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + query = [coordinates[0], coordinates[1]] + + return self._route_client.get_route_range( + format=ResponseFormat.JSON, + query=query, + **kwargs + ) + + + @distributed_trace + def get_route_directions_batch_sync( + self, + queries: List[str], + **kwargs: Any + ) -> RouteDirectionsBatchResult: + + """Sends batches of route directions requests. + The method return the result directly. + + :param queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type queries: List[str] + :return: RouteDirectionsBatchResult + :rtype: RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + batch_items = [{"query": f"?query={query}"} for query + in queries] if queries else [] + result = self._route_client.request_route_directions_batch_sync( + format=ResponseFormat.JSON, + route_directions_batch_queries={"batch_items": batch_items}, + **kwargs + ) + return RouteDirectionsBatchResult(summary=result.batch_summary, items=result.batch_items) + + @overload + def begin_get_route_directions_batch( + self, + batch_id: str, + **kwargs: Any + ) -> LROPoller[RouteDirectionsBatchResult]: + pass + + @overload + def begin_get_route_directions_batch( + self, + queries: List[str], + **kwargs: Any + ) -> LROPoller[RouteDirectionsBatchResult]: + pass + + @distributed_trace + def begin_get_route_directions_batch( + self, + **kwargs: Any + ) -> LROPoller[RouteDirectionsBatchResult]: + + """Sends batches of route direction queries. + The method returns a poller for retrieving the result later. + + :keyword queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :paramtype queries: List[str] + :keyword batch_id: Batch id for querying the operation. Required. + :paramtype batch_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.LROPoller[RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + queries=kwargs.pop('queries', None) + batch_id=kwargs.pop('batch_id', None) + + if batch_id: + poller = self._route_client.begin_get_route_directions_batch( + format=ResponseFormat.JSON, + batch_id=batch_id, + **kwargs + ) + return poller + + batch_items = [{"query": f"?query={query}"} for query + in queries] if queries else [] + batch_poller = self._route_client.begin_request_route_directions_batch( + format=ResponseFormat.JSON, + route_directions_batch_queries={"batch_items": batch_items}, + **kwargs + ) + batch_poller.batch_id = get_batch_id_from_poller(batch_poller.polling_method()) + return batch_poller + + @distributed_trace + def get_route_matrix( + self, + query: RouteMatrixQuery, + **kwargs: Any + ) -> RouteMatrixResult: + + """ + Calculates a matrix of route summaries for a set of routes defined by origin and destination locations. + The method return the result directly. + + The maximum size of a matrix for this method is 100 + (the number of origins multiplied by the number of destinations) + + :param query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Is either a model type or a IO type. Required. + :type query: ~azure.maps.route.models.RouteMatrixQuery or IO + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored during routing, + the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + return self._route_client.request_route_matrix_sync( + format=ResponseFormat.JSON, + route_matrix_query=query, + **kwargs + ) + + @overload + def begin_get_route_matrix_batch( + self, + query: RouteMatrixQuery, + **kwargs: Any + ) -> LROPoller[RouteMatrixResult]: + pass + + @overload + def begin_get_route_matrix_batch( + self, + matrix_id: str, + **kwargs: Any + ) -> LROPoller[RouteMatrixResult]: + pass + + @distributed_trace + def begin_get_route_matrix_batch( + self, + **kwargs: Any + ) -> LROPoller[RouteMatrixResult]: + + """ + Calculates a matrix of route summaries for a set of routes defined by origin and destination locations. + The method returns a poller for retrieving the result later. + + The maximum size of a matrix for this method is 700 + (the number of origins multiplied by the number of destinations) + + :keyword query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :paramtype query: ~azure.maps.route.models.RouteMatrixQuery + :keyword matrix_id: Matrix id received after the Matrix Route request was accepted successfully. + Required. + :paramtype matrix_id: str + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType`` =thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored during routing, + the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.LROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + query=kwargs.pop('query', None) + matrix_id = kwargs.pop('matrix_id', None) + + if matrix_id: + return self._route_client.begin_get_route_matrix( + matrix_id=matrix_id, + **kwargs + ) + + poller = self._route_client.begin_request_route_matrix( + format=ResponseFormat.JSON, + route_matrix_query=query, + **kwargs + ) + return poller diff --git a/sdk/maps/azure-maps-route/azure/maps/route/_version.py b/sdk/maps/azure-maps-route/azure/maps/route/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/maps/azure-maps-route/azure/maps/route/aio/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/__init__.py new file mode 100644 index 000000000000..e126fbc768b0 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._route_client_async import MapsRouteClient +__all__ = ['MapsRouteClient'] diff --git a/sdk/maps/azure-maps-route/azure/maps/route/aio/_base_client_async.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/_base_client_async.py new file mode 100644 index 000000000000..0fb5b838e380 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/_base_client_async.py @@ -0,0 +1,50 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from typing import Union, TYPE_CHECKING +from azure.core.pipeline.policies import AzureKeyCredentialPolicy +from azure.core.credentials import AzureKeyCredential +from .._generated.aio import MapsRouteClient as _MapsRouteClient +from .._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + +def _authentication_policy(credential): + authentication_policy = None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if isinstance(credential, AzureKeyCredential): + authentication_policy = AzureKeyCredentialPolicy( + name="subscription-key", credential=credential + ) + elif credential is not None and not hasattr(credential, "get_token"): + raise TypeError( + "Unsupported credential: {}. Use an instance of AzureKeyCredential " + "or a token credential from azure.identity".format(type(credential)) + ) + return authentication_policy + +class AsyncMapsRouteClientBase: + def __init__( + self, + credential, #type: Union[AzureKeyCredential, AsyncTokenCredential] + **kwargs #type: Any + ): + # type: (...) -> None + + self._maps_client = _MapsRouteClient( + credential=credential, # type: ignore + api_version=kwargs.pop("api_version", VERSION), + authentication_policy=kwargs.pop("authentication_policy", _authentication_policy(credential)), + **kwargs + ) + self._route_client = self._maps_client.route + + async def __aenter__(self): + await self._maps_client.__aenter__() # pylint:disable=no-member + return self + + async def __aexit__(self, *args): + return await self._maps_client.__aexit__(*args) # pylint:disable=no-member diff --git a/sdk/maps/azure-maps-route/azure/maps/route/aio/_route_client_async.py b/sdk/maps/azure-maps-route/azure/maps/route/aio/_route_client_async.py new file mode 100644 index 000000000000..89bd54f2a0fa --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/aio/_route_client_async.py @@ -0,0 +1,836 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# pylint: disable=unused-import,ungrouped-imports, R0904, C0302, W0212 +from typing import Any, List, Union, Tuple, overload +from azure.core.polling import AsyncLROPoller +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.credentials import AzureKeyCredential +from azure.core.credentials_async import AsyncTokenCredential +from ._base_client_async import AsyncMapsRouteClientBase + +from ..models import ( + RouteDirectionsBatchResult, + RouteDirections, + RouteRangeResult, + RouteMatrixResult, + RouteMatrixQuery, + LatLon +) + +from .._generated.models import ( + ResponseFormat +) + +def get_batch_id_from_poller(polling_method): + if hasattr(polling_method, "_operation"): + operation=polling_method._operation + return operation._location_url.split('/')[-1].split('?')[0] + return None + +# By default, use the latest supported API version +class MapsRouteClient(AsyncMapsRouteClientBase): + """Azure Maps Route REST APIs. + :param credential: + Credential needed for the client to connect to Azure. + :type credential: + ~azure.core.credentials.TokenCredential or ~azure.core.credentials.AzureKeyCredential + :keyword str base_url: + Supported Maps Services or Language resource base_url + (protocol and hostname, for example: 'https://us.atlas.microsoft.com'). + :keyword str client_id: + Specifies which account is intended for usage with the Azure AD security model. + It represents a unique ID for the Azure Maps account. + :keyword api_version: + The API version of the service to use for requests. It defaults to the latest service version. + Setting to an older version may result in reduced feature compatibility. + :paramtype api_version: str + """ + + def __init__( + self, + credential: Union[AzureKeyCredential, AsyncTokenCredential], + **kwargs: Any + )-> None: + + super().__init__( + credential=credential, **kwargs + ) + + # cSpell:disable + @distributed_trace_async + async def get_route_directions( + self, + route_points: Union[List[LatLon], List[Tuple]], + **kwargs: Any + ) -> RouteDirections: + """ + Returns a route between an origin and a destination, passing through waypoints if they are + specified. The route will take into account factors such as current traffic and the typical + road speeds on the requested day of the week and time of day. + + Information returned includes the distance, estimated travel time, and a representation of the + route geometry. Additional routing information such as optimized waypoint order or turn by turn + instructions is also available, depending on the options selected. + + :param route_points: The Coordinate from which the range calculation should start, coordinates as (lat, lon) + :type route_points: List[LatLon] or List[Tuple] + :keyword supporting_points: A GeoJSON Geometry collection representing sequence of coordinates + used as input for route reconstruction and for calculating zero or more alternative routes to + this reference route. + :paramtype supporting_points: ~azure.maps.route.models.GeoJsonGeometryCollection + :keyword avoid_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which all toll roads with vignettes are to be avoided, e.g. "AUS,CHE". Toll roads + with vignettes in countries not in the list are unaffected. + :paramtype avoid_vignette: list[str] + :keyword allow_vignette: This is a list of 3-character, ISO 3166-1, alpha-3 country codes of + countries in which toll roads with vignettes are allowed, e.g. "AUS,CHE". Specifying + **allowVignette** with some countries X is equivalent to specifying **avoidVignette** with all + countries but X. Specifying **allowVignette** with an empty list is the same as avoiding all + toll roads with vignettes. + :paramtype allow_vignette: list[str] + :keyword avoid_areas: A GeoJSON MultiPolygon representing list of areas to avoid. Only rectangle + polygons are supported. The maximum size of a rectangle is about 160x160 km. Maximum number of + avoided areas is **10**. + :paramtype avoid_areas: ~azure.maps.route.models.GeoJsonMultiPolygon + :keyword max_alternatives: Number of desired alternative routes to be calculated. Default: 0, + minimum: 0 and maximum: 5. Default value is None. + :paramtype max_alternatives: int + :keyword alternative_type: Controls the optimality, with respect to the given planning + criteria, of the calculated alternatives compared to the reference route. Known values are: + "anyRoute" and "betterRoute". Default value is None. + :paramtype alternative_type: str or ~azure.maps.route.models.AlternativeRouteType + :keyword min_deviation_distance: All alternative routes returned will follow the reference + route (see section POST Requests) from the origin point of the calculateRoute request for at + least this number of meters. Can only be used when reconstructing a route. The + minDeviationDistance parameter cannot be used in conjunction with arriveAt. Default value is + None. + :paramtype min_deviation_distance: int + :keyword min_deviation_time: All alternative routes returned will follow the reference route + (see section POST Requests) from the origin point of the calculateRoute request for at least + this number of seconds. Can only be used when reconstructing a route. The minDeviationTime + parameter cannot be used in conjunction with arriveAt. Default value is 0. + :paramtype min_deviation_time: int + :keyword instructions_type: If specified, guidance instructions will be returned. Note that the + instructionsType parameter cannot be used in conjunction with routeRepresentation=none. Known + values are: "coded", "text", and "tagged". Default value is None. + :paramtype instructions_type: str or ~azure.maps.route.models.RouteInstructionsType + :keyword language: The language parameter determines the language of the guidance messages. It + does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when + instructionsType=coded. Allowed values are (a subset of) the IETF language tags described. + Default value is None. + :paramtype language: str + :keyword compute_best_waypoint_order: Re-order the route waypoints using a fast heuristic + algorithm to reduce the route length. Yields best results when used in conjunction with + routeType *shortest*. Notice that origin and destination are excluded from the optimized + waypoint indices. To include origin and destination in the response, please increase all the + indices by 1 to account for the origin, and then add the destination as the final index. + Possible values are true or false. True computes a better order if possible, but is not allowed + to be used in conjunction with maxAlternatives value greater than 0 or in conjunction with + circle waypoints. False will use the locations in the given order and not allowed to be used in + conjunction with routeRepresentation *none*. Default value is None. + :paramtype compute_best_waypoint_order: bool + :keyword route_representation_for_best_order: Specifies the representation of the set of routes + provided as response. This parameter value can only be used in conjunction with + computeBestOrder=true. Known values are: "polyline", "summaryOnly", and "none". Default value + is None. + :paramtype route_representation_for_best_order: str or + ~azure.maps.route.models.RouteRepresentationForBestOrder + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword vehicle_heading: The directional heading of the vehicle in degrees starting at true + North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is + 180 degrees, west is 270 degrees. Possible values 0-359. Default value is None. + :paramtype vehicle_heading: int + :keyword report: Specifies which data should be reported for diagnosis purposes. The only + possible value is *effectiveSettings*. Reports the effective parameters or data used when + calling the API. In the case of defaulted parameters the default will be reflected where the + parameter was not specified by the caller. "effectiveSettings" Default value is None. + :paramtype report: str or ~azure.maps.route.models.Report + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). + :paramtype auxiliary_power_in_kw: float + :return: RouteDirections + :rtype: ~azure.maps.route.models.RouteDirections + :raises ~azure.core.exceptions.HttpResponseError: + """ + query_items="" + route_directions_body={} + if route_points: + query_items = ":".join([(str(route_point[0])+","+str(route_point[1])) for route_point in route_points]) + + supporting_points = kwargs.pop('supporting_points', None) + avoid_vignette = kwargs.pop('avoid_vignette', None) + allow_vignette = kwargs.pop('allow_vignette', None) + avoid_areas = kwargs.pop('avoid_areas', None) + if supporting_points or avoid_vignette or allow_vignette or avoid_areas is not None: + route_directions_body['supporting_points'] = supporting_points + route_directions_body['avoid_vignette'] = avoid_vignette + route_directions_body['allow_vignette'] = allow_vignette + route_directions_body['avoid_areas'] = avoid_areas + + if route_directions_body: + # import pdb; pdb.set_trace() + return await self._route_client.get_route_directions_with_additional_parameters( + format=ResponseFormat.JSON, + route_direction_parameters=route_directions_body, + route_points=query_items, + **kwargs + ) + return await self._route_client.get_route_directions( + format=ResponseFormat.JSON, + route_points=query_items, + **kwargs + ) + + # cSpell:disable + @distributed_trace_async + async def get_route_range( + self, + coordinates: Union[LatLon, Tuple], + **kwargs: Any + ) -> RouteRangeResult: + + """**Route Range (Isochrone) API** + + This service will calculate a set of locations that can be reached from the origin point based + on fuel, energy, time or distance budget that is specified. A polygon boundary (or Isochrone) + is returned in a counterclockwise orientation as well as the precise polygon center which was + the result of the origin point. + + :param coordinates: The Coordinate from which the range calculation should start, coordinates as (lat, lon) + :type coordinates: LatLon or Tuple + :keyword fuel_budget_in_liters: Fuel budget in liters that determines maximal range which can + be travelled using the specified Combustion Consumption Model.:code:`
` When + fuelBudgetInLiters is used, it is mandatory to specify a detailed Combustion Consumption + Model.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype fuel_budget_in_liters: float + :keyword energy_budget_in_kw_h: Electric energy budget in kilowatt hours (kWh) that determines + maximal range which can be travelled using the specified Electric Consumption + Model.:code:`
` When energyBudgetInkWh is used, it is mandatory to specify a detailed + Electric Consumption Model.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype energy_budget_in_kw_h: float + :keyword time_budget_in_sec: Time budget in seconds that determines maximal range which can be + travelled using driving time. The Consumption Model will only affect the range when routeType + is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, energyBudgetInkWh, timeBudgetInSec, + or distanceBudgetInMeters) must be used. Default value is None. + :paramtype time_budget_in_sec: float + :keyword distance_budget_in_meters: Distance budget in meters that determines maximal range + which can be travelled using driving distance. The Consumption Model will only affect the + range when routeType is eco.:code:`
` Exactly one budget (fuelBudgetInLiters, + energyBudgetInkWh, timeBudgetInSec, or distanceBudgetInMeters) must be used. Default value is + None. + :paramtype distance_budget_in_meters: float + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. + :paramtype use_traffic_data: bool + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. The max speed in the + vehicle profile is used to check whether a vehicle is allowed on motorways. + Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default + value is 0. + :paramtype vehicle_weight: int + :keyword is_commercial_vehicle: Whether the vehicle is used for commercial purposes. Commercial + vehicles may not be allowed to drive on some roads. Default value is False. + :paramtype is_commercial_vehicle: bool + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword vehicle_engine_type: Engine type of the vehicle. When a detailed Consumption Model is + specified, it must be consistent with the value of **vehicleEngineType**. Known values are: + "combustion" and "electric". Default value is None. + :paramtype vehicle_engine_type: str or ~azure.maps.route.models.VehicleEngineType + :keyword constant_speed_consumption_in_liters_per_hundred_km: Specifies the speed-dependent + component of consumption. + :paramtype constant_speed_consumption_in_liters_per_hundred_km: str + :keyword current_fuel_in_liters: Specifies the current supply of fuel in liters. + :paramtype current_fuel_in_liters: float + :keyword auxiliary_power_in_liters_per_hour: Specifies the amount of fuel consumed for + sustaining auxiliary systems of the vehicle, in liters per hour. + :paramtype auxiliary_power_in_liters_per_hour: float + :keyword fuel_energy_density_in_megajoules_per_liter: Specifies the amount of chemical energy + stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the + ***Efficiency** parameters for conversions between saved or consumed energy and fuel. + :paramtype fuel_energy_density_in_megajoules_per_liter: float + :keyword acceleration_efficiency: Specifies the efficiency of converting chemical energy stored + in fuel to kinetic energy when the vehicle accelerates *(i.e. + KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by converting + consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + :paramtype acceleration_efficiency: float + :keyword deceleration_efficiency: Specifies the efficiency of converting kinetic energy to + saved (not consumed) fuel when the vehicle decelerates *(i.e. + ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. Default + value is None. + :paramtype deceleration_efficiency: float + :keyword uphill_efficiency: Specifies the efficiency of converting chemical energy stored in + fuel to potential energy when the vehicle gains elevation *(i.e. + PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed* is obtained by + converting consumed fuel to chemical energy using **fuelEnergyDensityInMJoulesPerLiter**. + Default value is None. + :paramtype uphill_efficiency: float + :keyword downhill_efficiency: Specifies the efficiency of converting potential energy to saved + (not consumed) fuel when the vehicle loses elevation *(i.e. + ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved* is obtained by converting saved + (not consumed) fuel to energy using **fuelEnergyDensityInMJoulesPerLiter**. Default + value is None. + :paramtype downhill_efficiency: float + :keyword constant_speed_consumption_in_kw_h_per_hundred_km: Specifies the speed-dependent + component of consumption. Default value is None. + :paramtype constant_speed_consumption_in_kw_h_per_hundred_km: str + :keyword current_charge_in_kw_h: Specifies the current electric energy supply in kilowatt hours + (kWh). Default value is None. + :paramtype current_charge_in_kw_h: float + :keyword max_charge_in_kw_h: Specifies the maximum electric energy supply in kilowatt hours + (kWh) that may be stored in the vehicle's battery. Default value is None. + :paramtype max_charge_in_kw_h: float + :keyword auxiliary_power_in_kw: Specifies the amount of power consumed for sustaining auxiliary + systems, in kilowatts (kW). Default value is None. + :paramtype auxiliary_power_in_kw: float + :return: RouteRangeResult + :rtype: ~azure.maps.route.models.RouteRangeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + query = [coordinates[0], coordinates[1]] + + return await self._route_client.get_route_range( + format=ResponseFormat.JSON, + query=query, + **kwargs + ) + + + @distributed_trace_async + async def get_route_directions_batch_sync( + self, + queries: List[str], + **kwargs: Any + ) -> RouteDirectionsBatchResult: + + """Sends batches of route directions requests. + The method return the result directly. + + :param queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :type queries: List[str] + :return: RouteDirectionsBatchResult + :rtype: RouteDirectionsBatchResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + batch_items = [{"query": f"?query={query}"} for query + in queries] if queries else [] + result = await self._route_client.request_route_directions_batch_sync( + format=ResponseFormat.JSON, + route_directions_batch_queries={"batch_items": batch_items}, + **kwargs + ) + return RouteDirectionsBatchResult(summary=result.batch_summary, items=result.batch_items) + + @overload + def begin_get_route_directions_batch( + self, + batch_id: str, + **kwargs: Any + ) -> AsyncLROPoller[RouteDirectionsBatchResult]: + pass + + @overload + def begin_get_route_directions_batch( + self, + queries: List[str], + **kwargs: Any + ) -> AsyncLROPoller[RouteDirectionsBatchResult]: + pass + + @distributed_trace_async + async def begin_get_route_directions_batch( + self, + **kwargs: Any + ) -> AsyncLROPoller[RouteDirectionsBatchResult]: + + """Sends batches of route direction queries. + The method returns a poller for retrieving the result later. + + :keyword queries: The list of route directions queries/requests to + process. The list can contain a max of 700 queries for async and 100 queries for sync version + and must contain at least 1 query. Required. + :paramtype queries: List[str] + :keyword batch_id: Batch id for querying the operation. Required. + :paramtype batch_id: str + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteDirectionsBatchResult + :rtype: ~azure.core.polling.AsyncLROPoller[RouteDirectionsBatchResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + queries=kwargs.pop('queries', None) + batch_id=kwargs.pop('batch_id', None) + + if batch_id: + poller = await self._route_client.begin_get_route_directions_batch( + format=ResponseFormat.JSON, + batch_id=batch_id, + **kwargs + ) + return poller + + batch_items = [{"query": f"?query={query}"} for query + in queries] if queries else [] + batch_poller = await self._route_client.begin_request_route_directions_batch( + format=ResponseFormat.JSON, + route_directions_batch_queries={"batch_items": batch_items}, + **kwargs + ) + batch_poller.batch_id = get_batch_id_from_poller(batch_poller.polling_method()) + return batch_poller + + @distributed_trace_async + async def get_route_matrix( + self, + query: RouteMatrixQuery, + **kwargs: Any + ) -> RouteMatrixResult: + + """ + Calculates a matrix of route summaries for a set of routes defined by origin and destination locations. + The method return the result directly. + + The maximum size of a matrix for this method is 100 + (the number of origins multiplied by the number of destinations) + + :param query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Is either a model type or a IO type. Required. + :type query: ~azure.maps.route.models.RouteMatrixQuery or IO + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored during routing, + the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :return: RouteMatrixResult + :rtype: ~azure.maps.route.models.RouteMatrixResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await self._route_client.request_route_matrix_sync( + format=ResponseFormat.JSON, + route_matrix_query=query, + **kwargs + ) + + @overload + async def begin_get_route_matrix_batch( + self, + query: RouteMatrixQuery, + **kwargs: Any + ) -> AsyncLROPoller[RouteMatrixResult]: + pass + + @overload + async def begin_get_route_matrix_batch( + self, + matrix_id: str, + **kwargs: Any + ) -> AsyncLROPoller[RouteMatrixResult]: + pass + + @distributed_trace_async + async def begin_get_route_matrix_batch( + self, + **kwargs: Any + ) -> AsyncLROPoller[RouteMatrixResult]: + + """ + Calculates a matrix of route summaries for a set of routes defined by origin and destination locations. + The method returns a poller for retrieving the result later. + + The maximum size of a matrix for this method is 700 + (the number of origins multiplied by the number of destinations) + + :keyword query: The matrix of origin and destination coordinates to compute the + route distance, travel time and other summary for each cell of the matrix based on the input + parameters. The minimum and the maximum cell count supported are 1 and **700** for async and + **100** for sync respectively. For example, it can be 35 origins and 20 destinations or 25 + origins and 25 destinations for async API. Required. + :paramtype query: ~azure.maps.route.models.RouteMatrixQuery + :keyword matrix_id: Matrix id received after the Matrix Route request was accepted successfully. + Required. + :paramtype matrix_id: str + :keyword wait_for_results: Boolean to indicate whether to execute the request synchronously. If + set to true, user will get a 200 response if the request is finished under 120 seconds. + Otherwise, user will get a 202 response right away. Please refer to the API description for + more details on 202 response. **Supported only for async request**. Default value is None. + :paramtype wait_for_results: bool + :keyword compute_travel_time: Specifies whether to return additional travel times using + different types of traffic information (none, historic, live) as well as the default + best-estimate travel time. Known values are: "none" and "all". Default value is None. + :paramtype compute_travel_time: str or ~azure.maps.route.models.ComputeTravelTime + :keyword filter_section_type: Specifies which of the section types is reported in the route + response. :code:`
`:code:`
`For example if sectionType = pedestrian the sections which + are suited for pedestrians only are returned. Multiple types can be used. The default + sectionType refers to the travelMode input. By default travelMode is set to car. Known values + are: "carTrain", "country", "ferry", "motorway", "pedestrian", "tollRoad", "tollVignette", + "traffic", "travelMode", "tunnel", "carpool", and "urban". Default value is None. + :paramtype filter_section_type: str or ~azure.maps.route.models.SectionType + :keyword arrive_at: The date and time of arrival at the destination point. It must be specified + as a dateTime. When a time zone offset is not specified it will be assumed to be that of the + destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be + used in conjunction with departAt, minDeviationDistance or minDeviationTime. Default value is + None. + :paramtype arrive_at: ~datetime.datetime + :keyword depart_at: The date and time of departure from the origin point. Departure times apart + from now must be specified as a dateTime. When a time zone offset is not specified, it will be + assumed to be that of the origin point. The departAt value must be in the future in the + date-time format (1996-12-19T16:39:57-08:00). Default value is None. + :paramtype depart_at: ~datetime.datetime + :keyword vehicle_axle_weight: Weight per axle of the vehicle in kg. A value of 0 means that + weight restrictions per axle are not considered. Default value is 0. + :paramtype vehicle_axle_weight: int + :keyword vehicle_length: Length of the vehicle in meters. A value of 0 means that length + restrictions are not considered. Default value is 0. + :paramtype vehicle_length: float + :keyword vehicle_height: Height of the vehicle in meters. A value of 0 means that height + restrictions are not considered. Default value is 0. + :paramtype vehicle_height: float + :keyword vehicle_width: Width of the vehicle in meters. A value of 0 means that width + restrictions are not considered. Default value is 0. + :paramtype vehicle_width: float + :keyword vehicle_max_speed: Maximum speed of the vehicle in km/hour. Default value is 0. + :paramtype vehicle_max_speed: int + :keyword vehicle_weight: Weight of the vehicle in kilograms. Default value is 0. + :paramtype vehicle_weight: int + :keyword windingness: Level of turns for thrilling route. This parameter can only be used in + conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and "high". + Default value is None. + :paramtype windingness: str or ~azure.maps.route.models.WindingnessLevel + :keyword incline_level: Degree of hilliness for thrilling route. This parameter can only be + used in conjunction with ``routeType``=thrilling. Known values are: "low", "normal", and + "high". Default value is None. + :paramtype incline_level: str or ~azure.maps.route.models.InclineLevel + :keyword travel_mode: The mode of travel for the requested route. If not defined, default is + 'car'. Note that the requested travelMode may not be available for the entire route. Where the + requested travelMode is not available for a particular section, the travelMode element of the + response for that section will be "other". Note that travel modes bus, motorcycle, taxi and van + are BETA functionality. Full restriction data is not available in all areas. In + **calculateReachableRange** requests, the values bicycle and pedestrian must not be used. Known + values are: "car", "truck", "taxi", "bus", "van", "motorcycle", "bicycle", and "pedestrian". + Default value is None. + :paramtype travel_mode: str or ~azure.maps.route.models.TravelMode + :keyword avoid: Specifies something that the route calculation should try to avoid when + determining the route. Can be specified multiple times in one request, for example, + '&avoid=motorways&avoid=tollRoads&avoid=ferries'. In calculateReachableRange requests, the + value alreadyUsedRoads must not be used. Default value is None. + :paramtype avoid: list[str or ~azure.maps.route.models.RouteAvoidType] + :keyword use_traffic_data: Possible values: + * true - Do consider all available traffic information during routing + * false - Ignore current traffic data during routing. Note that although the current traffic + data is ignored during routing, + the effect of historic traffic on effective road speeds is still + incorporated. Default value is None. + :paramtype use_traffic_data: bool + :keyword route_type: The type of route requested. Known values are: "fastest", "shortest", + "eco", and "thrilling". Default value is None. + :paramtype route_type: str or ~azure.maps.route.models.RouteType + :keyword vehicle_load_type: Types of cargo that may be classified as hazardous materials and + restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, + plus generic classifications for use in other countries. Values beginning with USHazmat are for + US routing while otherHazmat should be used for all other countries. vehicleLoadType can be + specified multiple times. This parameter is currently only considered for travelMode=truck. + Known values are: "USHazmatClass1", "USHazmatClass2", "USHazmatClass3", "USHazmatClass4", + "USHazmatClass5", "USHazmatClass6", "USHazmatClass7", "USHazmatClass8", "USHazmatClass9", + "otherHazmatExplosive", "otherHazmatGeneral", and "otherHazmatHarmfulToWater". Default value is + None. + :paramtype vehicle_load_type: str or ~azure.maps.route.models.VehicleLoadType + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns RouteMatrixResult + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.maps.route.models.RouteMatrixResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + query=kwargs.pop('query', None) + matrix_id = kwargs.pop('matrix_id', None) + + if matrix_id: + return await self._route_client.begin_get_route_matrix( + matrix_id=matrix_id, + **kwargs + ) + + poller = await self._route_client.begin_request_route_matrix( + format=ResponseFormat.JSON, + route_matrix_query=query, + **kwargs + ) + return poller diff --git a/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py b/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py new file mode 100644 index 000000000000..6f3ba8bd9658 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/models/__init__.py @@ -0,0 +1,110 @@ + +from .._generated.models import ( + RouteRangeResult, + RouteDirections, + RouteInstructionsType, + ComputeTravelTime, + SectionType, + WindingnessLevel, + InclineLevel, + TravelMode, + RouteAvoidType, + RouteType, + VehicleLoadType, + VehicleEngineType, + RouteRepresentationForBestOrder, + AlternativeRouteType, + RouteMatrixQuery, + RouteMatrixResult, + RouteMatrixSummary, + RouteOptimizedWaypoint, + RouteSummary, + RouteGuidance, + Route, + RouteSectionTec, + BatchResultSummary, + GuidanceInstructionType, + JunctionType, + RouteLegSummary, + GeoJsonFeatureCollectionData, + GeoJsonGeometryCollectionData, +) + +from ._models import ( + LatLon, + BoundingBox, + GeoJsonObject, + GeoJsonFeatureData, + GeoJsonFeature, + GeoJsonFeatureCollection, + GeoJsonGeometry, + GeoJsonMultiLineString, + GeoJsonMultiPoint, + GeoJsonMultiPolygon, + GeoJsonPoint, + GeoJsonPolygon, + GeoJsonObjectType, + GeoJsonGeometryCollection, + RouteDirectionsBatchResult, + RouteDirectionsBatchItem, + RouteLeg, + TravelMode, + RouteDirectionsBatchItemResult, + GeoJsonMultiLineStringData, + GeoJsonMultiPolygonData, + GeoJsonMultiPointData +) + + +__all__ = [ + 'RouteRangeResult', + 'LatLon', + 'BoundingBox', + 'BatchResultSummary', + 'JunctionType', + 'GuidanceInstructionType', + 'RouteLegSummary', + 'RouteDirections', + 'RouteInstructionsType', + 'ComputeTravelTime', + 'SectionType', + 'WindingnessLevel', + 'InclineLevel', + 'TravelMode', + 'RouteAvoidType', + 'RouteType', + 'VehicleLoadType', + 'VehicleEngineType', + 'RouteDirectionsBatchResult', + 'RouteRepresentationForBestOrder', + 'AlternativeRouteType', + 'RouteMatrixQuery', + 'RouteMatrixResult', + 'Route', + 'RouteLeg', + 'RouteSummary', + 'RouteGuidance', + 'RouteMatrixSummary', + 'RouteDirectionsBatchItem', + 'RouteOptimizedWaypoint', + 'GeoJsonObject', + 'GeoJsonFeatureData', + 'GeoJsonObjectType', + 'GeoJsonFeature', + 'GeoJsonFeatureCollection', + 'GeoJsonGeometry', + 'GeoJsonMultiLineString', + 'GeoJsonMultiPoint', + 'GeoJsonMultiPolygon', + 'GeoJsonPoint', + 'GeoJsonPolygon', + 'GeoJsonGeometryCollection', + 'TravelMode', + 'RouteDirectionsBatchItemResult', + 'RouteSectionTec', + 'GeoJsonFeatureCollectionData', + 'GeoJsonGeometryCollectionData', + 'GeoJsonMultiLineStringData', + 'GeoJsonMultiPolygonData', + 'GeoJsonMultiPointData' +] diff --git a/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py b/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py new file mode 100644 index 000000000000..d9890a012875 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/models/_models.py @@ -0,0 +1,1101 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +# pylint: disable=unused-import,ungrouped-imports, super-init-not-called, W0212, C0302 +from typing import List, Optional, Union, NamedTuple +from enum import Enum, EnumMeta +from six import with_metaclass +import msrest.serialization + +from azure.core import CaseInsensitiveEnumMeta +from .._generated.models import ( + BatchResult as GenBatchResult, + RouteLeg as GenRouteLeg, + BatchResultSummary, + ErrorDetail, + RouteReport, + RouteSectionTec, + GuidanceInstructionType +) + +class LatLon(NamedTuple): + """Represents coordinate latitude and longitude + + :keyword lat: The coordinate as latitude. + :paramtype lat: float + :keyword lon: The coordinate as longitude. + :paramtype lon: float + """ + lat: float = 0 + lon: float = 0 + +class BoundingBox(NamedTuple): + """Represents information about the coordinate range + + :keyword west: The westmost value of coordinates. + :paramtype west: float + :keyword south: The southmost value of coordinates. + :paramtype south: float + :keyword east: The eastmost value of coordinates. + :paramtype east: float + :keyword north: The northmost value of coordinates. + :paramtype north: float + """ + west: float = 0.0 + south: float = 0.0 + east: float = 0.0 + north: float = 0.0 + +# cSpell:disable +class RouteSection(object): + """Route sections contain additional information about parts of a route. + Each section contains at least the elements ``startPointIndex``, ``endPointIndex``, and ``sectionType``. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar start_point_index: Index of the first point (offset 0) in the route this section applies + to. + :vartype start_point_index: int + :ivar end_point_index: Index of the last point (offset 0) in the route this section applies to. + :vartype end_point_index: int + :ivar section_type: Section types of the reported route response. Known values are: + "CAR_TRAIN", "COUNTRY", "FERRY", "MOTORWAY", "PEDESTRIAN", "TOLL_ROAD", "TOLL_VIGNETTE", + "TRAFFIC", "TRAVEL_MODE", "TUNNEL", "CARPOOL", and "URBAN". + :vartype section_type: str or ~azure.maps.route.models.SectionType + :ivar travel_mode: Travel mode for the calculated route. The value will be set to ``other`` if + the requested mode of transport is not possible in this section. Known values are: "car", + "truck", "taxi", "bus", "van", "motorcycle", "bicycle", "pedestrian", and "other". + :vartype travel_mode: str or ~azure.maps.route.models.TravelMode + :ivar simple_category: Type of the incident. Can currently be JAM, ROAD_WORK, ROAD_CLOSURE, or + OTHER. See "tec" for detailed information. Known values are: "JAM", "ROAD_WORK", + "ROAD_CLOSURE", and "OTHER". + :vartype simple_category: str or ~azure.maps.route.models.SimpleCategory + :ivar effective_speed_in_kmh: Effective speed of the incident in km/h, averaged over its entire + length. + :vartype effective_speed_in_kmh: int + :ivar delay_in_seconds: Delay in seconds caused by the incident. + :vartype delay_in_seconds: int + :ivar delay_magnitude: The magnitude of delay caused by the incident. These values correspond + to the values of the response field ty of the `Get Traffic Incident Detail API + `_. Known values + are: "0", "1", "2", "3", and "4". + :vartype delay_magnitude: str or ~azure.maps.route.models.DelayMagnitude + :ivar tec: Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + :vartype tec: ~azure.maps.route.models.RouteSectionTec + """ + + _validation = { + "start_point_index": {"readonly": True}, + "end_point_index": {"readonly": True}, + "section_type": {"readonly": True}, + "travel_mode": {"readonly": True}, + "simple_category": {"readonly": True}, + "effective_speed_in_kmh": {"readonly": True}, + "delay_in_seconds": {"readonly": True}, + "delay_magnitude": {"readonly": True}, + } + + _attribute_map = { + "start_point_index": {"key": "startPointIndex", "type": "int"}, + "end_point_index": {"key": "endPointIndex", "type": "int"}, + "section_type": {"key": "sectionType", "type": "str"}, + "travel_mode": {"key": "travelMode", "type": "str"}, + "simple_category": {"key": "simpleCategory", "type": "str"}, + "effective_speed_in_kmh": {"key": "effectiveSpeedInKmh", "type": "int"}, + "delay_in_seconds": {"key": "delayInSeconds", "type": "int"}, + "delay_magnitude": {"key": "magnitudeOfDelay", "type": "str"}, + "tec": {"key": "tec", "type": "RouteSectionTec"}, + } + + def __init__(self, *, tec: Optional["RouteSectionTec"] = None, **kwargs): + """ + :keyword tec: Details of the traffic event, using definitions in the `TPEG2-TEC + `_ standard. Can contain effectCode and causes + elements. + :paramtype tec: ~azure.maps.route.models.RouteSectionTec + """ + super().__init__(**kwargs) + self.start_point_index = None + self.end_point_index = None + self.section_type = None + self.travel_mode = None + self.simple_category = None + self.effective_speed_in_kmh = None + self.delay_in_seconds = None + self.delay_magnitude = None + self.tec = tec + +class RouteDirectionsBatchItemResult(object): + """The result of the query. RouteDirections if the query completed successfully, ErrorResponse otherwise. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: The error object. + :vartype error: ~azure.maps.route.models.ErrorDetail + :ivar format_version: Format Version property. + :vartype format_version: str + :ivar routes: Routes array. + :vartype routes: list[~azure.maps.route.models.Route] + :ivar optimized_waypoints: Optimized sequence of waypoints. It shows the index from the user + provided waypoint sequence for the original and optimized list. For instance, a response: + + .. code-block:: + + + + + + + + means that the original sequence is [0, 1, 2] and optimized sequence is [1, 2, 0]. Since the + index starts by 0 the original is "first, second, third" while the optimized is "second, third, + first". + :vartype optimized_waypoints: list[~azure.maps.route.models.RouteOptimizedWaypoint] + :ivar report: Reports the effective settings used in the current call. + :vartype report: RouteReport + """ + + _validation = { + "format_version": {"readonly": True}, + "routes": {"readonly": True}, + "optimized_waypoints": {"readonly": True}, + } + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + "format_version": {"key": "formatVersion", "type": "str"}, + "routes": {"key": "routes", "type": "[Route]"}, + "optimized_waypoints": {"key": "optimizedWaypoints", "type": "[RouteOptimizedWaypoint]"}, + "report": {"key": "report", "type": "RouteReport"}, + } + + def __init__( + self, *, error: Optional["ErrorDetail"] = None, report: Optional["RouteReport"] = None, **kwargs + ): + """ + :keyword error: The error object. + :paramtype error: ~azure.maps.route.models.ErrorDetail + :keyword report: Reports the effective settings used in the current call. + :paramtype report: ~azure.maps.route.models.RouteReport + """ + super().__init__(report=report, error=error, **kwargs) + self.error = error + self.format_version = None + self.routes = None + self.optimized_waypoints = None + self.report = report + +class RouteDirectionsBatchItem(object): + """An item returned from Route Directions Batch service call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar result: The result of the query. RouteDirections if the query completed successfully, + ErrorResponse otherwise. + :vartype result: RouteDirectionsBatchItemResult + """ + + _validation = { + "result": {"readonly": True}, + } + + _attribute_map = { + "result": {"key": "result", "type": "RouteDirectionsBatchItemResult"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.result = None + +class RouteDirectionsBatchResult(object): + """This object is returned from a successful Route Directions Batch service call. + + Variables are only populated by the server, and will be ignored when sending a request. + + :keyword summary: Summary of the results for the batch request. + :paramtype summary: ~azure.maps.route.models.BatchResultSummary + :keyword items: Array containing the batch results. + :paramtype items: list[RouteDirectionsBatchItem] + """ + def __init__( + self, + **kwargs + ): + self.summary = kwargs.get('summary', None) + self.items = kwargs.get('items', None) + +class RouteLeg(GenRouteLeg): + """A description of a part of a route, comprised of a list of points. + Each additional waypoint provided in the request will result in an additional + leg in the returned route. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar summary: Summary object for route section. + :vartype summary: ~azure.maps.route.models.RouteLegSummary + :ivar points: Points array. + :vartype points: list[LatLon] + """ + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.summary = None + self.points = None + +class GeoJsonObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON object types - Point, + MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and + FeatureCollection. + """ + + GEO_JSON_POINT = "Point" #: ``GeoJSON Point`` geometry. + GEO_JSON_MULTI_POINT = "MultiPoint" #: ``GeoJSON MultiPoint`` geometry. + GEO_JSON_LINE_STRING = "LineString" #: ``GeoJSON LineString`` geometry. + GEO_JSON_MULTI_LINE_STRING = "MultiLineString" #: ``GeoJSON MultiLineString`` geometry. + GEO_JSON_POLYGON = "Polygon" #: ``GeoJSON Polygon`` geometry. + GEO_JSON_MULTI_POLYGON = "MultiPolygon" #: ``GeoJSON MultiPolygon`` geometry. + GEO_JSON_GEOMETRY_COLLECTION = "GeometryCollection" #: ``GeoJSON GeometryCollection`` geometry. + GEO_JSON_FEATURE = "Feature" #: ``GeoJSON Feature`` object. + GEO_JSON_FEATURE_COLLECTION = "FeatureCollection" #: ``GeoJSON FeatureCollection`` object. + +class GeoJsonObject(msrest.serialization.Model): + """A valid ``GeoJSON`` object. + Please refer to `RFC 7946 `_ for details. + + You probably want to use the sub-classes and not this class directly. Known + sub-classes are: GeoJsonFeature, GeoJsonFeatureCollection, GeoJsonGeometry, + GeoJsonGeometryCollection, GeoJsonLineString, GeoJsonMultiLineString, + GeoJsonMultiPoint, GeoJsonMultiPolygon, GeoJsonPoint, GeoJsonPolygon. + + All required parameters must be populated in order to send to Azure. + + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'type': {'required': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + } + + _subtype_map = { + 'type': {'Feature': 'GeoJsonFeature', 'FeatureCollection': 'GeoJsonFeatureCollection', + 'GeoJsonGeometry': 'GeoJsonGeometry', 'GeometryCollection': 'GeoJsonGeometryCollection', + 'LineString': 'GeoJsonLineString', 'MultiLineString': 'GeoJsonMultiLineString', + 'MultiPoint': 'GeoJsonMultiPoint', 'MultiPolygon': 'GeoJsonMultiPolygon', + 'Point': 'GeoJsonPoint', 'Polygon': 'GeoJsonPolygon' + } + } + + def __init__( + self, + _type: Union[str, GeoJsonObjectType] = None, + **kwargs + ): + super(GeoJsonObject, self).__init__(**kwargs) + self.type = _type # type: Optional[Union[str, GeoJsonObjectType]] + +class GeoJsonFeatureData(msrest.serialization.Model): + """GeoJsonFeatureData. + + All required parameters must be populated in order to send to Azure. + + :param geometry: Required. A valid ``GeoJSON`` object. Please refer to `RFC 7946 + `_ for details. + :type geometry: ~azure.maps.route.models.GeoJsonObject + :param properties: Properties can contain any additional metadata about the ``Feature``. Value + can be any JSON object or a JSON null value. + :type properties: object + :param feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :type feature_type: str + """ + + _validation = { + 'geometry': {'required': True}, + } + + _attribute_map = { + 'geometry': {'key': 'geometry', 'type': 'GeoJsonObject'}, + 'properties': {'key': 'properties', 'type': 'object'}, + 'feature_type': {'key': 'featureType', 'type': 'str'}, + } + + def __init__( + self, + *, + geometry: "GeoJsonObject", + properties: Optional[object] = None, + feature_type: Optional[str] = None, + **kwargs + ): + super(GeoJsonFeatureData, self).__init__(**kwargs) + self.geometry = geometry + self.properties = properties + self.feature_type = feature_type + +class GeoJsonFeature(GeoJsonObject, GeoJsonFeatureData): + """A valid ``GeoJSON Feature`` object type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param geometry: Required. A valid ``GeoJSON`` object. Please refer to `RFC 7946 + `_ for details. + :type geometry: ~azure.maps.route.models.GeoJsonObject + :param properties: Properties can contain any additional metadata about the ``Feature``. Value + can be any JSON object or a JSON null value. + :type properties: object + :keyword feature_type: The type of the feature. The value depends on the data model the current + feature is part of. Some data models may have an empty value. + :paramtype feature_type: str + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'geometry': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'geometry': {'key': 'geometry', 'type': 'GeoJsonObject'}, + 'properties': {'key': 'properties', 'type': 'object'}, + 'feature_type': {'key': 'featureType', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + geometry: "GeoJsonObject", + properties: Optional[object] = None, + feature_type: Optional[str] = None, + **kwargs + ): + super(GeoJsonFeature, self).__init__( + geometry=geometry, properties=properties, feature_type=feature_type, **kwargs + ) + self.geometry = geometry + self.properties = properties + self.feature_type = feature_type + self.type = 'Feature' # type: str + + +class GeoJsonFeatureCollectionData(msrest.serialization.Model): + """GeoJsonFeatureCollectionData. + + All required parameters must be populated in order to send to Azure. + + :param features: Required. Contains a list of valid ``GeoJSON Feature`` objects. + :type features: list[~azure.maps.route.models.GeoJsonFeature] + """ + + _validation = { + 'features': {'required': True}, + } + + _attribute_map = { + 'features': {'key': 'features', 'type': '[GeoJsonFeature]'}, + } + + def __init__( + self, + *, + features: List["GeoJsonFeature"], + **kwargs + ): + super(GeoJsonFeatureCollectionData, self).__init__(**kwargs) + self.features = features + + +class GeoJsonFeatureCollection(GeoJsonObject, GeoJsonFeatureCollectionData): + """A valid ``GeoJSON FeatureCollection`` object type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param features: Required. Contains a list of valid ``GeoJSON Feature`` objects. + :type features: list[~azure.maps.route.models.GeoJsonFeature] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'features': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'features': {'key': 'features', 'type': '[GeoJsonFeature]'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + features: List["GeoJsonFeature"], + **kwargs + ): + super(GeoJsonFeatureCollection, self).__init__(features=features, **kwargs) + self.features = features + self.type = 'FeatureCollection' # type: str + + +class GeoJsonGeometry(GeoJsonObject): + """A valid ``GeoJSON`` geometry object. + The type must be one of the seven valid GeoJSON geometry types - + Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'type': {'required': True}, + } + + _attribute_map = { + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(GeoJsonGeometry, self).__init__(**kwargs) + self.type = 'GeoJsonGeometry' # type: str + + +class GeoJsonGeometryCollectionData(msrest.serialization.Model): + """GeoJsonGeometryCollectionData. + + All required parameters must be populated in order to send to Azure. + + :param geometries: Required. Contains a list of valid ``GeoJSON`` geometry objects. **Note** + that coordinates in GeoJSON are in x, y order (longitude, latitude). + :type geometries: list[~azure.maps.route.models.GeoJsonObject] + """ + + _validation = { + 'geometries': {'required': True}, + } + + _attribute_map = { + 'geometries': {'key': 'geometries', 'type': '[GeoJsonObject]'}, + } + + def __init__( + self, + *, + geometries: List["GeoJsonObject"], + **kwargs + ): + super(GeoJsonGeometryCollectionData, self).__init__(**kwargs) + self.geometries = geometries + + +class GeoJsonGeometryCollection(GeoJsonObject, GeoJsonGeometryCollectionData): + """A valid ``GeoJSON GeometryCollection`` object type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param geometries: Required. Contains a list of valid ``GeoJSON`` geometry objects. **Note** + that coordinates in GeoJSON are in x, y order (longitude, latitude). + :type geometries: list[~azure.maps.route.models.GeoJsonObject] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'geometries': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'geometries': {'key': 'geometries', 'type': '[GeoJsonObject]'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + geometries: List["GeoJsonObject"], + **kwargs + ): + super(GeoJsonGeometryCollection, self).__init__(geometries=geometries, **kwargs) + self.geometries = geometries + self.type = 'GeometryCollection' # type: str + + +class GeoJsonLineStringData(msrest.serialization.Model): + """GeoJsonLineStringData. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson LineString`` geometry. + :type coordinates: list[LatLon] + """ + + _validation = { + 'coordinates': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, + } + + def __init__( + self, + *, + coordinates: List[LatLon], + **kwargs + ): + super(GeoJsonLineStringData, self).__init__(**kwargs) + self.coordinates = coordinates + +class GeoJsonLineString(GeoJsonObject, GeoJsonLineStringData): + """A valid ``GeoJSON LineString`` geometry type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson LineString`` geometry. + :type coordinates: list[LatLon] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'coordinates': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': '[LatLon]'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + coordinates: List[LatLon], + **kwargs + ): + super(GeoJsonLineString, self).__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = 'LineString' # type: str + + +class GeoJsonMultiLineStringData(object): + """GeoJsonMultiLineStringData. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson MultiLineString`` geometry. + :type coordinates: list[list[list[LatLon]]] + """ + + def __init__( + self, + **kwargs + ): + super(GeoJsonMultiLineStringData, self).__init__(**kwargs) + self.coordinates = kwargs['coordinates'] + +class GeoJsonMultiPointData(object): + """Data contained by a ``GeoJson MultiPoint``. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson MultiPoint`` geometry. + :type coordinates: list[list[LatLon]] + """ + + def __init__( + self, + **kwargs + ): + super(GeoJsonMultiPointData, self).__init__(**kwargs) + self.coordinates = kwargs['coordinates'] + +class GeoJsonMultiPolygonData(object): + """GeoJsonMultiPolygonData. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Contains a list of valid ``GeoJSON Polygon`` objects. **Note** + that coordinates in GeoJSON are in x, y order (longitude, latitude). + :type coordinates: list[list[list[list[LatLon]]]] + """ + + def __init__( + self, + **kwargs + ): + super(GeoJsonMultiPolygonData, self).__init__(**kwargs) + self.coordinates = kwargs['coordinates'] + +class GeoJsonMultiLineString(GeoJsonObject, GeoJsonMultiLineStringData): + """A valid ``GeoJSON MultiLineString`` geometry type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson MultiLineString`` geometry. + :type coordinates: list[list[LatLon]] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + def __init__( + self, + *, + coordinates: List[List[LatLon]], + **kwargs + ): + super(GeoJsonMultiLineString, self).__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = 'MultiLineString' # type: str + +class GeoJsonMultiPoint(GeoJsonObject, GeoJsonMultiPointData): + """A valid ``GeoJSON MultiPoint`` geometry type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson MultiPoint`` geometry. + :type coordinates: list[LatLon] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + def __init__( + self, + *, + coordinates: List[LatLon], + **kwargs + ): + super(GeoJsonMultiPoint, self).__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = 'MultiPoint' # type: str + +class GeoJsonMultiPolygon(GeoJsonObject, GeoJsonMultiPolygonData): + """A valid ``GeoJSON MultiPolygon`` object type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Contains a list of valid ``GeoJSON Polygon`` objects. **Note** + that coordinates in GeoJSON are in x, y order (longitude, latitude). + :type coordinates: list[list[list[LatLon]]] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'coordinates': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': '[[[LatLon]]]'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + coordinates: List[List[List[LatLon]]], + **kwargs + ): + super(GeoJsonMultiPolygon, self).__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = 'MultiPolygon' # type: str + self.type = 'MultiPolygon' # type: str + + +class GeoJsonPointData(msrest.serialization.Model): + """Data contained by a ``GeoJson Point``. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. A ``Position`` is an array of numbers with two or more elements. + The first two elements are *longitude* and *latitude*, precisely in that order. + *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 + `_ for details. + :type coordinates: LatLon + """ + + _validation = { + 'coordinates': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': 'LatLon'}, + } + + def __init__( + self, + *, + coordinates: LatLon, + **kwargs + ): + super(GeoJsonPointData, self).__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonPoint(GeoJsonObject, GeoJsonPointData): + """A valid ``GeoJSON Point`` geometry type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. A ``Position`` is an array of numbers with two or more elements. + The first two elements are *longitude* and *latitude*, precisely in that order. + *Altitude/Elevation* is an optional third element. Please refer to `RFC 7946 + `_ for details. + :type coordinates: LatLon + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or ~azure.maps.route._models.GeoJsonObjectType + """ + + _validation = { + 'coordinates': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': 'LatLon'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + coordinates: LatLon, + **kwargs + ): + super(GeoJsonPoint, self).__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = 'Point' # type: str + + +class GeoJsonPolygonData(msrest.serialization.Model): + """GeoJsonPolygonData. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson Polygon`` geometry type. + :type coordinates: list[list[LatLon]] + """ + + _validation = { + 'coordinates': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, + } + + def __init__( + self, + *, + coordinates: List[List[LatLon]], + **kwargs + ): + super(GeoJsonPolygonData, self).__init__(**kwargs) + self.coordinates = coordinates + + +class GeoJsonPolygon(GeoJsonObject, GeoJsonPolygonData): + """A valid ``GeoJSON Polygon`` geometry type. + Please refer to `RFC 7946 `_ for details. + + All required parameters must be populated in order to send to Azure. + + :param coordinates: Required. Coordinates for the ``GeoJson Polygon`` geometry type. + :type coordinates: list[list[LatLon]] + :param type: Required. Specifies the ``GeoJSON`` type. Must be one of the nine valid GeoJSON + object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, + GeometryCollection, Feature and FeatureCollection.Constant filled by server. Possible values + include: "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", + "GeometryCollection", "Feature", "FeatureCollection". + :type type: str or GeoJsonObjectType + """ + + _validation = { + 'coordinates': {'required': True}, + 'type': {'required': True}, + } + + _attribute_map = { + 'coordinates': {'key': 'coordinates', 'type': '[[LatLon]]'}, + 'type': {'key': 'type', 'type': 'str'}, + } + + def __init__( + self, + *, + coordinates: List[List[LatLon]], + **kwargs + ): + super(GeoJsonPolygon, self).__init__(coordinates=coordinates, **kwargs) + self.coordinates = coordinates + self.type = 'Polygon' # type: str + +class TravelMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Travel mode for the calculated route. The value will be set to ``other`` if the requested mode + of transport is not possible in this section. + """ + + #: The returned routes are optimized for cars. + CAR = "car" + #: The returned routes are optimized for commercial vehicles, like for trucks. + TRUCK = "truck" + #: The returned routes are optimized for taxis. BETA functionality. + TAXI = "taxi" + #: The returned routes are optimized for buses, including the use of bus only lanes. BETA + #: functionality. + BUS = "bus" + #: The returned routes are optimized for vans. BETA functionality. + VAN = "van" + #: The returned routes are optimized for motorcycles. BETA functionality. + MOTORCYCLE = "motorcycle" + #: The returned routes are optimized for bicycles, including use of bicycle lanes. + BICYCLE = "bicycle" + #: The returned routes are optimized for pedestrians, including the use of sidewalks. + PEDESTRIAN = "pedestrian" + #: The given mode of transport is not possible in this section + OTHER = "other" + +class RouteInstruction(object): # pylint: disable=too-many-instance-attributes + """A set of attributes describing a maneuver, e.g. 'Turn right', 'Keep left', + 'Take the ferry', 'Take the motorway', 'Arrive'. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar route_offset_in_meters: Distance from the start of the route to the point of the + instruction. + :vartype route_offset_in_meters: int + :ivar travel_time_in_seconds: Estimated travel time up to the point corresponding to + routeOffsetInMeters. + :vartype travel_time_in_seconds: int + :ivar point: A location represented as a latitude and longitude. + :vartype point: LatLon + :ivar point_index: The index of the point in the list of polyline "points" corresponding to the + point of the instruction. + :vartype point_index: int + :ivar instruction_type: Type of the instruction, e.g., turn or change of road form. Known + values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", + and "LOCATION_WAYPOINT". + :vartype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + :ivar road_numbers: The road number(s) of the next significant road segment(s) after the + maneuver, or of the road(s) to be followed. Example: ["E34", "N205"]. + :vartype road_numbers: list[str] + :ivar exit_number: The number(s) of a highway exit taken by the current maneuver. If an exit + has multiple exit numbers, they will be separated by "," and possibly aggregated by "-", e.g., + "10, 13-15". + :vartype exit_number: str + :ivar street: Street name of the next significant road segment after the maneuver, or of the + street that should be followed. + :vartype street: str + :ivar signpost_text: The text on a signpost which is most relevant to the maneuver, or to the + direction that should be followed. + :vartype signpost_text: str + :ivar country_code: 3-character `ISO 3166-1 `_ + alpha-3 country code. E.g. USA. + :vartype country_code: str + :ivar state_code: A subdivision (e.g., state) of the country, represented by the second part of + an `ISO 3166-2 `_ code. This is only available for + some countries like the US, Canada, and Mexico. + :vartype state_code: str + :ivar junction_type: The type of the junction where the maneuver takes place. For larger + roundabouts, two separate instructions are generated for entering and leaving the roundabout. + Known values are: "REGULAR", "ROUNDABOUT", and "BIFURCATION". + :vartype junction_type: str or ~azure.maps.route.models.JunctionType + :ivar turn_angle_in_degrees: Indicates the direction of an instruction. If junctionType + indicates a turn instruction: + + + * 180 = U-turn + * [-179, -1] = Left turn + * 0 = Straight on (a '0 degree' turn) + * [1, 179] = Right turn + + If junctionType indicates a bifurcation instruction: + + + * <0 - keep left + * >0 - keep right. + :vartype turn_angle_in_degrees: int + :ivar roundabout_exit_number: This indicates which exit to take at a roundabout. + :vartype roundabout_exit_number: str + :ivar possible_combine_with_next: It is possible to optionally combine the instruction with the + next one. This can be used to build messages like "Turn left and then turn right". + :vartype possible_combine_with_next: bool + :ivar driving_side: Indicates left-hand vs. right-hand side driving at the point of the + maneuver. Known values are: "LEFT" and "RIGHT". + :vartype driving_side: str or ~azure.maps.route.models.DrivingSide + :ivar maneuver: A code identifying the maneuver. Known values are: "ARRIVE", "ARRIVE_LEFT", + "ARRIVE_RIGHT", "DEPART", "STRAIGHT", "KEEP_RIGHT", "BEAR_RIGHT", "TURN_RIGHT", "SHARP_RIGHT", + "KEEP_LEFT", "BEAR_LEFT", "TURN_LEFT", "SHARP_LEFT", "MAKE_UTURN", "ENTER_MOTORWAY", + "ENTER_FREEWAY", "ENTER_HIGHWAY", "TAKE_EXIT", "MOTORWAY_EXIT_LEFT", "MOTORWAY_EXIT_RIGHT", + "TAKE_FERRY", "ROUNDABOUT_CROSS", "ROUNDABOUT_RIGHT", "ROUNDABOUT_LEFT", "ROUNDABOUT_BACK", + "TRY_MAKE_UTURN", "FOLLOW", "SWITCH_PARALLEL_ROAD", "SWITCH_MAIN_ROAD", "ENTRANCE_RAMP", + "WAYPOINT_LEFT", "WAYPOINT_RIGHT", and "WAYPOINT_REACHED". + :vartype maneuver: str or ~azure.maps.route.models.GuidanceManeuver + :ivar message: A human-readable message for the maneuver. + :vartype message: str + :ivar combined_message: A human-readable message for the maneuver combined with the message + from the next instruction. Sometimes it is possible to combine two successive instructions into + a single instruction making it easier to follow. When this is the case the + possibleCombineWithNext flag will be true. For example: + + .. code-block:: + + 10. Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam + 11. Follow Einsteinweg/A10/E22 towards Ring Amsterdam + + The possibleCombineWithNext flag on instruction 10 is true. This indicates to the clients of + coded guidance that it can be combined with instruction 11. The instructions will be combined + automatically for clients requesting human-readable guidance. The combinedMessage field + contains the combined message: + + .. code-block:: + + Turn left onto Einsteinweg/A10/E22 towards Ring Amsterdam + then follow Einsteinweg/A10/E22 towards Ring Amsterdam. + :vartype combined_message: str + """ + + _validation = { + "route_offset_in_meters": {"readonly": True}, + "travel_time_in_seconds": {"readonly": True}, + "point_index": {"readonly": True}, + "road_numbers": {"readonly": True}, + "exit_number": {"readonly": True}, + "street": {"readonly": True}, + "signpost_text": {"readonly": True}, + "country_code": {"readonly": True}, + "state_code": {"readonly": True}, + "junction_type": {"readonly": True}, + "turn_angle_in_degrees": {"readonly": True}, + "roundabout_exit_number": {"readonly": True}, + "possible_combine_with_next": {"readonly": True}, + "driving_side": {"readonly": True}, + "maneuver": {"readonly": True}, + "message": {"readonly": True}, + "combined_message": {"readonly": True}, + } + + _attribute_map = { + "route_offset_in_meters": {"key": "routeOffsetInMeters", "type": "int"}, + "travel_time_in_seconds": {"key": "travelTimeInSeconds", "type": "int"}, + "point": {"key": "point", "type": "LatLongPair"}, + "point_index": {"key": "pointIndex", "type": "int"}, + "instruction_type": {"key": "instructionType", "type": "str"}, + "road_numbers": {"key": "roadNumbers", "type": "[str]"}, + "exit_number": {"key": "exitNumber", "type": "str"}, + "street": {"key": "street", "type": "str"}, + "signpost_text": {"key": "signpostText", "type": "str"}, + "country_code": {"key": "countryCode", "type": "str"}, + "state_code": {"key": "stateCode", "type": "str"}, + "junction_type": {"key": "junctionType", "type": "str"}, + "turn_angle_in_degrees": {"key": "turnAngleInDecimalDegrees", "type": "int"}, + "roundabout_exit_number": {"key": "roundaboutExitNumber", "type": "str"}, + "possible_combine_with_next": {"key": "possibleCombineWithNext", "type": "bool"}, + "driving_side": {"key": "drivingSide", "type": "str"}, + "maneuver": {"key": "maneuver", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "combined_message": {"key": "combinedMessage", "type": "str"}, + } + + def __init__( + self, + *, + point: Optional["LatLon"] = None, + instruction_type: Optional[Union[str, "GuidanceInstructionType"]] = None, + **kwargs + ): + """ + :keyword point: A location represented as a latitude and longitude. + :paramtype point: ~azure.maps.route.models.LatLongPair + :keyword instruction_type: Type of the instruction, e.g., turn or change of road form. Known + values are: "TURN", "ROAD_CHANGE", "LOCATION_DEPARTURE", "LOCATION_ARRIVAL", "DIRECTION_INFO", + and "LOCATION_WAYPOINT". + :paramtype instruction_type: str or ~azure.maps.route.models.GuidanceInstructionType + """ + super().__init__(**kwargs) + self.route_offset_in_meters = None + self.travel_time_in_seconds = None + self.point = point + self.point_index = None + self.instruction_type = instruction_type + self.road_numbers = None + self.exit_number = None + self.street = None + self.signpost_text = None + self.country_code = None + self.state_code = None + self.junction_type = None + self.turn_angle_in_degrees = None + self.roundabout_exit_number = None + self.possible_combine_with_next = None + self.driving_side = None + self.maneuver = None + self.message = None + self.combined_message = None diff --git a/sdk/maps/azure-maps-route/azure/maps/route/py.typed b/sdk/maps/azure-maps-route/azure/maps/route/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/maps/azure-maps-route/azure/maps/route/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/dev_requirements.txt b/sdk/maps/azure-maps-route/dev_requirements.txt new file mode 100644 index 000000000000..d85375f9cdba --- /dev/null +++ b/sdk/maps/azure-maps-route/dev_requirements.txt @@ -0,0 +1,5 @@ +-e ../../../tools/azure-devtools +-e ../../../tools/azure-sdk-tools +-e ../../core/azure-core +-e ../../identity/azure-identity +aiohttp>=3.0; python_version >= '3.6' \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/README.md b/sdk/maps/azure-maps-route/samples/README.md new file mode 100644 index 000000000000..2cc45b8b5ddc --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/README.md @@ -0,0 +1,61 @@ +--- +page_type: sample +languages: + - python +products: + - azure + - azure-maps-route +--- + +# Samples for Azure Maps Route client library for Python + +These code samples show common scenario operations with the Azure Maps Route client library. + +Authenticate the client with a Azure Maps Route [API Key Credential](https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys): + +[samples authentication](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/sample_authentication.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py)) + +Then for common Azure Maps Route operations: + +* Get Route Directions: [sample_get_route_directions.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py)) + +* Get Route Range: [sample_get_route_range.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/sample_get_route_range.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py)) + +* Request Route Matrix: [sample_request_route_matrix.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py)) + +* Request Begin Get Route Directions batch [sample_begin_get_route_directions_batch( +.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py)) + +* Request Get Route Directions Batch Sync [sample_get_route_directions_batch_sync.py](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py) ([async version](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py)) + +## Prerequisites + +* Python 3.6 or later is required to use this package +* You must have an [Azure subscription](https://azure.microsoft.com/free/) +* A deployed Maps Services resource. You can create the resource via [Azure Portal][azure_portal] or [Azure CLI][azure_cli]. + +## Setup + +1. Install the Azure Maps Route client library for Python with [pip](https://pypi.org/project/pip/): + + ```bash + pip install azure-maps-route --pre + ``` + +2. Clone or download [this repository](https://github.com/Azure/azure-sdk-for-python) +3. Open this sample folder in [Visual Studio Code](https://code.visualstudio.com) or your IDE of choice. + +## Running the samples + +1. Open a terminal window and `cd` to the directory that the samples are saved in. +2. Set the environment variables specified in the sample file you wish to run. +3. Follow the usage described in the file, e.g. `python sample_fuzzy_route.py` + +## Next steps + +Check out the [API reference documentation](https://docs.microsoft.com/rest/api/maps/route) +to learn more about what you can do with the Azure Maps Route client library. + + +[azure_portal]: https://portal.azure.com +[azure_cli]: https://docs.microsoft.com/cli/azure diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py new file mode 100644 index 000000000000..a301f83df817 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_authentication_async.py @@ -0,0 +1,73 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_authentication_async.py +DESCRIPTION: + This sample demonstrates how to authenticate with the Azure Maps Route + service with an Subscription key. See more details about authentication here: + https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys +USAGE: + python sample_authentication_async.py + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your Azure Maps subscription key + - TENANT_ID - your tenant ID that wants to access Azure Maps account + - CLIENT_ID - your client ID that wants to access Azure Maps account + - CLIENT_SECRET - your client secret that wants to access Azure Maps account + - AZURE_MAPS_CLIENT_ID - your Azure Maps client ID +""" + +import asyncio +import os +import sys + +async def authentication_maps_service_client_with_subscription_key_credential_async(): + # [START create_maps_route_service_client_with_key_async] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route.aio import MapsRouteClient + + subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + # [END create_maps_route_service_client_with_key_async] + + async with maps_route_client: + result = await maps_route_client.get_route_directions( + route_points=[(52.50931,13.42936), (52.50274,13.43872)] + ) + print(result) + +async def authentication_maps_service_client_with_aad_credential_async(): + """DefaultAzureCredential will use the values from these environment + variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, AZURE_MAPS_CLIENT_ID + """ + # [START create_maps_route_service_client_with_aad_async] + from azure.identity.aio import DefaultAzureCredential + from azure.maps.route.aio import MapsRouteClient + + credential = DefaultAzureCredential() + maps_client_id = os.getenv("AZURE_MAPS_CLIENT_ID") + + maps_route_client = MapsRouteClient(client_id=maps_client_id, credential=credential) + # [END create_maps_route_service_client_with_aad_async] + + async with maps_route_client: + result = await maps_route_client.get_route_directions( + route_points=[(52.50931,13.42936), (52.50274,13.43872)] + ) + print(result) + + +async def main(): + await authentication_maps_service_client_with_subscription_key_credential_async() + await authentication_maps_service_client_with_aad_credential_async() + +if __name__ == '__main__': + if sys.platform == 'win32': + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + asyncio.run(main()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py new file mode 100644 index 000000000000..18dac1530f85 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_begin_get_route_directions_batch_async.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_begin_get_route_directions_batch_async.py +DESCRIPTION: + This sample demonstrates how to sends batches of route direction queries. +USAGE: + python begin_get_route_directions_batch_async.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import asyncio +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + +async def begin_get_route_directions_batch_async(): + from azure.core.credentials import AzureKeyCredential + from azure.maps.route.aio import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + async with maps_route_client: + result = await maps_route_client.begin_get_route_directions_batch( + queries=[ + "47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + ], + polling=True, + ) + + print("Get route directions batch batch_id to fetch the result later") + print(result.batch_id) + +if __name__ == '__main__': + asyncio.run(begin_get_route_directions_batch_async()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py new file mode 100644 index 000000000000..836cad354de8 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_async.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_directions_async.py +DESCRIPTION: + This sample demonstrates how to perform get route directions with list of lat/lon. +USAGE: + python sample_get_route_directions_async.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import asyncio +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + +async def get_route_directions(): + # [START get_route_directions_async] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route.aio import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + async with maps_route_client: + result = await maps_route_client.get_route_directions( + route_points=[(52.50931,13.42936), (52.50274,13.43872)] + ) + + print("Get Route Directions with list of coordinates:") + print(result.routes[0].summary) + print(result.routes[0].sections[0]) + # [END get_route_directions_async] + +if __name__ == '__main__': + asyncio.run(get_route_directions()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py new file mode 100644 index 000000000000..4cd079eb3089 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_directions_batch_sync_async.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_directions_batch_sync.py +DESCRIPTION: + This sample demonstrates how to perform get route directions batch job asynchronously with given query strings. +USAGE: + python sample_get_route_directions_batch_sync.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import asyncio +import os +from re import M + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + +async def get_route_directions_batch_sync_async(): + # [START get_route_directions_batch_sync_async] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route.aio import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + async with maps_route_client: + result = await maps_route_client.get_route_directions_batch_sync( + queries=[ + "47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + ] + ) + + print("Get route directions batch sync") + print(result.summary.total_requests) + print(result.items[0].response.routes[0].sections[0]) + # [END get_route_directions_batch_sync] + +if __name__ == '__main__': + asyncio.run(get_route_directions_batch_sync_async()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py new file mode 100644 index 000000000000..2ce89e02eb03 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_matrix_async.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_matrix_async.py +DESCRIPTION: + This sample demonstrates how to perform get route matrix result with given request object. +USAGE: + python sample_get_route_matrix_async.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import asyncio +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + +async def get_route_matrix_async(): + # [START get_route_matrix_async] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route.aio import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + request_obj = { + "origins": { + "type": "MultiPoint", + "coordinates": [ + [ + 4.85106, + 52.36006 + ], + [ + 4.85056, + 52.36187 + ] + ] + }, + "destinations": { + "type": "MultiPoint", + "coordinates": [ + [ + 4.85003, + 52.36241 + ], + [ + 13.42937, + 52.50931 + ] + ] + } + } + + async with maps_route_client: + result = await maps_route_client.get_route_matrix(query=request_obj) + + print("Get Route Matrix with given request object:") + print(result.matrix[0][0].response.summary.length_in_meters) + print(result.summary) + # [END get_route_matrix_async] + +if __name__ == '__main__': + asyncio.run(get_route_matrix_async()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py new file mode 100644 index 000000000000..84d712485fbf --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/async_samples/sample_get_route_range_async.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_range_async.py +DESCRIPTION: + This sample demonstrates how to perform get route range with list of lat/lon. +USAGE: + python sample_get_route_range_async.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import asyncio +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + +async def get_route_range(): + # [START get_route_range_async] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route.aio import MapsRouteClient + from azure.maps.route.models import LatLon + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + async with maps_route_client: + result = await maps_route_client.get_route_range( + coordinates=LatLon(52.50931,13.42936), + time_budget_in_sec=6000 + ) + + print("Get Route Range with coordinates and time budget:") + print(result.reachable_range.center) + print(result.reachable_range.boundary[0]) + # [END get_route_range_async] + +if __name__ == '__main__': + asyncio.run(get_route_range()) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_authentication.py b/sdk/maps/azure-maps-route/samples/sample_authentication.py new file mode 100644 index 000000000000..ca76405d96cb --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/sample_authentication.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_authentication.py +DESCRIPTION: + This sample demonstrates how to authenticate with the Azure Maps Route + service with an Subscription key. See more details about authentication here: + https://docs.microsoft.com/azure/azure-maps/how-to-manage-account-keys +USAGE: + python sample_authentication.py + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your Azure Maps subscription key + - TENANT_ID - your tenant ID that wants to access Azure Maps account + - CLIENT_ID - your client ID that wants to access Azure Maps account + - CLIENT_SECRET - your client secret that wants to access Azure Maps account + - AZURE_MAPS_CLIENT_ID - your Azure Maps client ID +""" + +import os + +def authentication_maps_service_client_with_subscription_key_credential(): + # [START create_maps_route_service_client_with_key] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route import MapsRouteClient + + subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + # [END create_maps_route_service_client_with_key] + + result = maps_route_client.get_route_range(coordinates=(52.50931,13.42936), time_budget_in_sec=6000) + + print(result) + + +def authentication_maps_service_client_with_aad_credential(): + """DefaultAzureCredential will use the values from these environment + variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, AZURE_MAPS_CLIENT_ID + """ + # [START create_maps_route_service_client_with_aad] + from azure.identity import DefaultAzureCredential + from azure.maps.route import MapsRouteClient + + credential = DefaultAzureCredential() + maps_client_id = os.getenv("AZURE_MAPS_CLIENT_ID") + + maps_route_client = MapsRouteClient(client_id=maps_client_id, credential=credential) + # [END create_maps_route_service_client_with_aad] + + result = maps_route_client.get_route_range(coordinates=(52.50931,13.42936), time_budget_in_sec=6000) + + print(result) + + +if __name__ == '__main__': + authentication_maps_service_client_with_subscription_key_credential() + authentication_maps_service_client_with_aad_credential() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py b/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py new file mode 100644 index 000000000000..08e21b6f79c8 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/sample_begin_get_route_directions_batch.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_begin_get_route_directions_batch.py +DESCRIPTION: + This sample demonstrates how to sends batches of route direction queries. +USAGE: + python begin_get_route_directions_batch.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + +def begin_get_route_directions_batch(): + from azure.core.credentials import AzureKeyCredential + from azure.maps.route import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + result = maps_route_client.begin_get_route_directions_batch( + queries=[ + "47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + ] + ) + + print("Get route directions batch batch_id to fetch the result later") + print(result.batch_id) + +if __name__ == '__main__': + begin_get_route_directions_batch() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py b/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py new file mode 100644 index 000000000000..3fbf8b1e7108 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_directions.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_directions.py +DESCRIPTION: + This sample demonstrates how to perform get route directions with list of lat/lon. +USAGE: + python sample_get_route_directions.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + +def get_route_directions(): + # [START get_route_directions] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + result = maps_route_client.get_route_directions( + route_points=[(52.50931,13.42936), (52.50274,13.43872)], + avoid_vignette=["AUS", "CHE"] + ) + + print("Get Route Directions with list of coordinates:") + print(result.routes[0].summary) + print(result.routes[0].sections[0]) + # [END get_route_directions] + +if __name__ == '__main__': + get_route_directions() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py b/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py new file mode 100644 index 000000000000..5896e3e387c1 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_directions_batch_sync.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_directions_batch_sync.py +DESCRIPTION: + This sample demonstrates how to perform get route directions batch job synchronously with given query strings. +USAGE: + python sample_get_route_directions_batch_sync.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + +def get_route_directions_batch_sync(): + # [START get_route_directions_batch_sync] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + result = maps_route_client.get_route_directions_batch_sync( + queries=[ + "47.620659,-122.348934:47.610101,-122.342015&travelMode=bicycle&routeType=eco&traffic=false" + ] + ) + + print("Get route directions batch sync") + print(result.summary.total_requests) + print(result.items[0].response.routes[0].sections[0]) + # [END get_route_directions_batch_sync] + +if __name__ == '__main__': + get_route_directions_batch_sync() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py b/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py new file mode 100644 index 000000000000..496456b4a84b --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_matrix.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_matrix.py +DESCRIPTION: + This sample demonstrates how to perform get route matrix result with given request object. +USAGE: + python sample_get_route_matrix.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + + +def get_route_matrix(): + # [START get_route_matrix] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + request_obj = { + "origins": { + "type": "MultiPoint", + "coordinates": [ + [ + 4.85106, + 52.36006 + ], + [ + 4.85056, + 52.36187 + ] + ] + }, + "destinations": { + "type": "MultiPoint", + "coordinates": [ + [ + 4.85003, + 52.36241 + ], + [ + 13.42937, + 52.50931 + ] + ] + } + } + + result = maps_route_client.get_route_matrix(query=request_obj) + + print("Get Route Matrix with given request object:") + print(result.summary) + # [END get_route_matrix] + +if __name__ == '__main__': + get_route_matrix() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/samples/sample_get_route_range.py b/sdk/maps/azure-maps-route/samples/sample_get_route_range.py new file mode 100644 index 000000000000..43dc3872ed68 --- /dev/null +++ b/sdk/maps/azure-maps-route/samples/sample_get_route_range.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: sample_get_route_range.py +DESCRIPTION: + This sample demonstrates how to perform get route range with given lat/lon. +USAGE: + python sample_get_route_range.py + + Set the environment variables with your own values before running the sample: + - AZURE_SUBSCRIPTION_KEY - your subscription key +""" +import os + +subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY") + +def get_route_range(): + # [START get_route_range] + from azure.core.credentials import AzureKeyCredential + from azure.maps.route import MapsRouteClient + + maps_route_client = MapsRouteClient(credential=AzureKeyCredential(subscription_key)) + + result = maps_route_client.get_route_range(coordinates=(52.50931,13.42936), time_budget_in_sec=6000) + + print("Get Route Range with coordinates and time budget:") + print(result.reachable_range.center) + print(result.reachable_range.boundary[0]) + # [END get_route_range] + +if __name__ == '__main__': + get_route_range() \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/sdk_packaging.toml b/sdk/maps/azure-maps-route/sdk_packaging.toml new file mode 100644 index 000000000000..6c1fc55130d8 --- /dev/null +++ b/sdk/maps/azure-maps-route/sdk_packaging.toml @@ -0,0 +1,9 @@ +[packaging] +package_name = "azure-maps-route" +package_nspkg = "azure-maps-nspkg" +package_pprint_name = "Map Route" +package_doc_id = "" +is_stable = false +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true diff --git a/sdk/maps/azure-maps-route/setup.py b/sdk/maps/azure-maps-route/setup.py new file mode 100644 index 000000000000..dc99019bf56f --- /dev/null +++ b/sdk/maps/azure-maps-route/setup.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python + +#------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +#-------------------------------------------------------------------------- + +import re +import os.path +from io import open +from setuptools import find_packages, setup + +# Change the PACKAGE_NAME only to change folder and different name +PACKAGE_NAME = "azure-maps-route" +PACKAGE_PPRINT_NAME = "Maps Route" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace('-', '/') +# a-b-c => a.b.c +namespace_name = PACKAGE_NAME.replace('-', '.') + +# azure v0.x is not compatible with this package +# azure v0.x used to have a __version__ attribute (newer versions don't) +try: + import azure + try: + ver = azure.__version__ + raise Exception( + 'This package is incompatible with azure=={}. '.format(ver) + + 'Uninstall it with "pip uninstall azure".' + ) + except AttributeError: + pass +except ImportError: + pass + +# Version extraction inspired from 'requests' +with open(os.path.join(package_folder_path, 'version.py') + if os.path.exists(os.path.join(package_folder_path, 'version.py')) + else os.path.join(package_folder_path, '_version.py'), 'r') as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', + fd.read(), re.MULTILINE).group(1) + +if not version: + raise RuntimeError('Cannot find version information') + +with open('README.md', encoding='utf-8') as f: + readme = f.read() +with open('CHANGELOG.md', encoding='utf-8') as f: + changelog = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), + long_description=readme + '\n\n' + changelog, + long_description_content_type='text/markdown', + license='MIT License', + author='Microsoft Corporation', + author_email='azpysdkhelp@microsoft.com', + url='https://github.com/Azure/azure-sdk-for-python', + classifiers=[ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "License :: OSI Approved :: MIT License", + ], + zip_safe=False, + packages=find_packages(exclude=[ + 'tests', + 'azure', + 'azure.maps', + ]), + install_requires=[ + 'msrest>=0.6.21', + 'azure-common~=1.1', + 'azure-mgmt-core>=1.3.0,<2.0.0', + ] +) diff --git a/sdk/maps/azure-maps-route/swagger/README.md b/sdk/maps/azure-maps-route/swagger/README.md new file mode 100644 index 000000000000..76deca8a1b4d --- /dev/null +++ b/sdk/maps/azure-maps-route/swagger/README.md @@ -0,0 +1,47 @@ +# Azure Maps Route for Python + +> see https://aka.ms/autorest + +### Setup +Install Autorest v3 +```ps +npm install -g autorest +``` + +### Generation +```ps +cd +autorest --v3 --python +``` + +### Settings +```yaml +tag: '1.0' +input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/2e88f0e0951d1cdbe59db4dafbc48c93a723bfa2/specification/maps/data-plane/Route/preview/1.0/route.json +output-folder: ../azure/maps/route/_generated +namespace: azure.maps.route +package-name: azure-maps-route +no-namespace-folders: true +license-header: MICROSOFT_MIT_NO_VERSION +credential-scopes: https://atlas.microsoft.com/.default +clear-output-folder: true +python: true +no-async: false +add-credential: false +title: MapsRouteClient +disable-async-iterators: true +python-sdks-folder: $(python-sdks-folder) +python3-only: true +version-tolerant: true +models-mode: msrest +show-operations: true +only-path-and-body-parameters-positional: true +``` + +```yaml +directive: +- from: swagger-document + where: $.securityDefinitions + transform: | + $["SharedKey"]["in"] = "header"; +``` diff --git a/sdk/maps/azure-maps-route/tests/conftest.py b/sdk/maps/azure-maps-route/tests/conftest.py new file mode 100644 index 000000000000..f3d1daa909f8 --- /dev/null +++ b/sdk/maps/azure-maps-route/tests/conftest.py @@ -0,0 +1,31 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import os + +import pytest + +from devtools_testutils import ( + add_general_regex_sanitizer, + add_header_regex_sanitizer, + add_oauth_response_sanitizer, + test_proxy +) + +# autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method +# @pytest.fixture(scope="session", autouse=True) +# def start_proxy(test_proxy): +# return + +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + subscription_key = os.environ.get("SUBSCRIPTION_KEY", "subscription-key") + tenant_id = os.environ.get("MAPS_TENANT_ID", "tenant-id") + client_secret = os.environ.get("MAPS_CLIENT_SECRET", "MyClientSecret") + add_general_regex_sanitizer(regex=subscription_key, value="AzureMapsSubscriptionKey") + add_general_regex_sanitizer(regex=tenant_id, value="MyTenantId") + add_general_regex_sanitizer(regex=client_secret, value="MyClientSecret") + # add_oauth_response_sanitizer() diff --git a/sdk/maps/azure-maps-route/tests/recordings/test_route_client.pyTestMapsRouteClienttest_get_route_directions.json b/sdk/maps/azure-maps-route/tests/recordings/test_route_client.pyTestMapsRouteClienttest_get_route_directions.json new file mode 100644 index 000000000000..e16054afbb2b --- /dev/null +++ b/sdk/maps/azure-maps-route/tests/recordings/test_route_client.pyTestMapsRouteClienttest_get_route_directions.json @@ -0,0 +1,184 @@ +{ + "Entries": [ + { + "RequestUri": "https://atlas.microsoft.com/route/directions/json?api-version=1.0.0b1\u0026query=52.50931%2C13.42936%3A52.50274%2C13.43872\u0026vehicleAxleWeight=0\u0026vehicleWidth=0.0\u0026vehicleHeight=0.0\u0026vehicleLength=0.0\u0026vehicleMaxSpeed=0\u0026vehicleWeight=0\u0026vehicleCommercial=false", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "subscription-key": "AzureMapsSubscriptionKey", + "User-Agent": "azsdk-python-maps-route/1.0-preview Python/3.9.13 (Windows-10-10.0.22621-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Cache-Control": "no-transform, no-cache", + "Content-Length": "1796", + "Content-Type": "application/json; charset=utf-8", + "Date": "Thu, 13 Oct 2022 00:16:40 GMT", + "Pragma": "no-cache", + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "Vary": "Accept-Encoding", + "X-Cache": "CONFIG_NOCACHE", + "X-Content-Type-Options": "nosniff", + "x-ms-azuremaps-region": "West US 2", + "X-MSEdge-Ref": "Ref A: 2499D855AAAD422CA664F9E5DCEAF235 Ref B: TPE30EDGE0918 Ref C: 2022-10-13T00:16:40Z" + }, + "ResponseBody": { + "formatVersion": "0.0.12", + "routes": [ + { + "summary": { + "lengthInMeters": 1147, + "travelTimeInSeconds": 129, + "trafficDelayInSeconds": 0, + "trafficLengthInMeters": 0, + "departureTime": "2022-10-13T02:16:40\u002B02:00", + "arrivalTime": "2022-10-13T02:18:49\u002B02:00" + }, + "legs": [ + { + "summary": { + "lengthInMeters": 1147, + "travelTimeInSeconds": 129, + "trafficDelayInSeconds": 0, + "trafficLengthInMeters": 0, + "departureTime": "2022-10-13T02:16:40\u002B02:00", + "arrivalTime": "2022-10-13T02:18:49\u002B02:00" + }, + "points": [ + { + "latitude": 52.5093, + "longitude": 13.42937 + }, + { + "latitude": 52.50904, + "longitude": 13.42913 + }, + { + "latitude": 52.50895, + "longitude": 13.42904 + }, + { + "latitude": 52.50868, + "longitude": 13.4288 + }, + { + "latitude": 52.5084, + "longitude": 13.42857 + }, + { + "latitude": 52.50816, + "longitude": 13.42839 + }, + { + "latitude": 52.50791, + "longitude": 13.42825 + }, + { + "latitude": 52.50757, + "longitude": 13.42772 + }, + { + "latitude": 52.50752, + "longitude": 13.42785 + }, + { + "latitude": 52.50742, + "longitude": 13.42809 + }, + { + "latitude": 52.50735, + "longitude": 13.42824 + }, + { + "latitude": 52.5073, + "longitude": 13.42837 + }, + { + "latitude": 52.50696, + "longitude": 13.4291 + }, + { + "latitude": 52.50673, + "longitude": 13.42961 + }, + { + "latitude": 52.50619, + "longitude": 13.43092 + }, + { + "latitude": 52.50608, + "longitude": 13.43116 + }, + { + "latitude": 52.50574, + "longitude": 13.43195 + }, + { + "latitude": 52.50564, + "longitude": 13.43218 + }, + { + "latitude": 52.50528, + "longitude": 13.43299 + }, + { + "latitude": 52.50513, + "longitude": 13.43336 + }, + { + "latitude": 52.505, + "longitude": 13.43366 + }, + { + "latitude": 52.50464, + "longitude": 13.43451 + }, + { + "latitude": 52.50451, + "longitude": 13.43482 + }, + { + "latitude": 52.50444, + "longitude": 13.43499 + }, + { + "latitude": 52.50418, + "longitude": 13.43564 + }, + { + "latitude": 52.50364, + "longitude": 13.4369 + }, + { + "latitude": 52.50343, + "longitude": 13.43738 + }, + { + "latitude": 52.5033, + "longitude": 13.43767 + }, + { + "latitude": 52.50275, + "longitude": 13.43874 + } + ] + } + ], + "sections": [ + { + "startPointIndex": 0, + "endPointIndex": 28, + "sectionType": "TRAVEL_MODE", + "travelMode": "car" + } + ] + } + ] + } + } + ], + "Variables": {} +} diff --git a/sdk/maps/azure-maps-route/tests/recordings/test_route_client.pyTestMapsRouteClienttest_get_route_range.json b/sdk/maps/azure-maps-route/tests/recordings/test_route_client.pyTestMapsRouteClienttest_get_route_range.json new file mode 100644 index 000000000000..5988379863f9 --- /dev/null +++ b/sdk/maps/azure-maps-route/tests/recordings/test_route_client.pyTestMapsRouteClienttest_get_route_range.json @@ -0,0 +1,242 @@ +{ + "Entries": [ + { + "RequestUri": "https://atlas.microsoft.com/route/range/json?api-version=1.0.0b1\u0026query=50.97452,5.86605\u0026timeBudgetInSec=6000.0\u0026vehicleAxleWeight=0\u0026vehicleWidth=0.0\u0026vehicleHeight=0.0\u0026vehicleLength=0.0\u0026vehicleMaxSpeed=0\u0026vehicleWeight=0\u0026vehicleCommercial=false", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Connection": "keep-alive", + "subscription-key": "AzureMapsSubscriptionKey", + "User-Agent": "azsdk-python-maps-route/1.0-preview Python/3.9.13 (Windows-10-10.0.22621-SP0)" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Cache-Control": "no-transform, no-cache", + "Content-Length": "2195", + "Content-Type": "application/json; charset=utf-8", + "Date": "Thu, 13 Oct 2022 00:16:41 GMT", + "Pragma": "no-cache", + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "Vary": "Accept-Encoding", + "X-Cache": "CONFIG_NOCACHE", + "X-Content-Type-Options": "nosniff", + "x-ms-azuremaps-region": "West US 2", + "X-MSEdge-Ref": "Ref A: 8F5A3CE1E3304FC996D31E50E18B1258 Ref B: TPE30EDGE0918 Ref C: 2022-10-13T00:16:40Z" + }, + "ResponseBody": { + "formatVersion": "0.0.1", + "reachableRange": { + "center": { + "latitude": 50.97452, + "longitude": 5.86605 + }, + "boundary": [ + { + "latitude": 52.19343, + "longitude": 5.72585 + }, + { + "latitude": 52.19378, + "longitude": 5.60227 + }, + { + "latitude": 52.24224, + "longitude": 5.47546 + }, + { + "latitude": 52.26774, + "longitude": 5.20307 + }, + { + "latitude": 52.30604, + "longitude": 5.14534 + }, + { + "latitude": 52.33373, + "longitude": 4.91255 + }, + { + "latitude": 52.11988, + "longitude": 4.67653 + }, + { + "latitude": 52.11056, + "longitude": 4.6471 + }, + { + "latitude": 51.93177, + "longitude": 4.4399 + }, + { + "latitude": 51.87002, + "longitude": 4.32523 + }, + { + "latitude": 51.69725, + "longitude": 4.21751 + }, + { + "latitude": 51.49769, + "longitude": 3.77494 + }, + { + "latitude": 51.2102, + "longitude": 3.59263 + }, + { + "latitude": 50.68885, + "longitude": 3.93768 + }, + { + "latitude": 50.49589, + "longitude": 3.93722 + }, + { + "latitude": 50.4538, + "longitude": 3.90252 + }, + { + "latitude": 50.28611, + "longitude": 4.48031 + }, + { + "latitude": 50.20208, + "longitude": 4.56647 + }, + { + "latitude": 50.10755, + "longitude": 4.97366 + }, + { + "latitude": 50.09283, + "longitude": 5.02918 + }, + { + "latitude": 49.91769, + "longitude": 5.25036 + }, + { + "latitude": 49.87977, + "longitude": 5.26519 + }, + { + "latitude": 49.77595, + "longitude": 5.54465 + }, + { + "latitude": 49.75803, + "longitude": 5.56317 + }, + { + "latitude": 49.75706, + "longitude": 5.77634 + }, + { + "latitude": 49.9233, + "longitude": 5.94205 + }, + { + "latitude": 49.9348, + "longitude": 6.0833 + }, + { + "latitude": 50.01229, + "longitude": 6.13391 + }, + { + "latitude": 50.08942, + "longitude": 6.2758 + }, + { + "latitude": 49.88837, + "longitude": 6.54512 + }, + { + "latitude": 50.00492, + "longitude": 6.6107 + }, + { + "latitude": 49.94769, + "longitude": 6.8971 + }, + { + "latitude": 50.22922, + "longitude": 6.68836 + }, + { + "latitude": 50.22978, + "longitude": 7.00975 + }, + { + "latitude": 50.16467, + "longitude": 7.59464 + }, + { + "latitude": 50.34621, + "longitude": 7.63528 + }, + { + "latitude": 50.44604, + "longitude": 7.79885 + }, + { + "latitude": 50.83557, + "longitude": 8.01587 + }, + { + "latitude": 51.067, + "longitude": 7.70357 + }, + { + "latitude": 51.38747, + "longitude": 7.74341 + }, + { + "latitude": 51.53296, + "longitude": 7.85994 + }, + { + "latitude": 51.68222, + "longitude": 7.36076 + }, + { + "latitude": 51.8553, + "longitude": 7.29545 + }, + { + "latitude": 52.01617, + "longitude": 7.05678 + }, + { + "latitude": 51.82713, + "longitude": 6.67268 + }, + { + "latitude": 51.81133, + "longitude": 6.48424 + }, + { + "latitude": 51.94915, + "longitude": 6.34863 + }, + { + "latitude": 52.23839, + "longitude": 6.24098 + }, + { + "latitude": 52.24021, + "longitude": 6.17566 + }, + { + "latitude": 52.33411, + "longitude": 6.00979 + } + ] + } + } + } + ], + "Variables": {} +} diff --git a/sdk/maps/azure-maps-route/tests/route_preparer.py b/sdk/maps/azure-maps-route/tests/route_preparer.py new file mode 100644 index 000000000000..1ea0695e6acd --- /dev/null +++ b/sdk/maps/azure-maps-route/tests/route_preparer.py @@ -0,0 +1,15 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import functools +from devtools_testutils import EnvironmentVariableLoader + +MapsRoutePreparer = functools.partial( + EnvironmentVariableLoader, "maps", + subscription_key="", + maps_client_id="fake_client_id", + maps_client_secret="fake_secret", + maps_tenant_id="fake_tenant_id", +) \ No newline at end of file diff --git a/sdk/maps/azure-maps-route/tests/test_route_client.py b/sdk/maps/azure-maps-route/tests/test_route_client.py new file mode 100644 index 000000000000..f936e203162c --- /dev/null +++ b/sdk/maps/azure-maps-route/tests/test_route_client.py @@ -0,0 +1,75 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +from azure.core.credentials import AccessToken, AzureKeyCredential +from azure.maps.route import MapsRouteClient +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy, is_live +from route_preparer import MapsRoutePreparer + +class TestMapsRouteClient(AzureRecordedTestCase): + def setup_method(self, method): + self.client = MapsRouteClient( + credential=AzureKeyCredential(os.environ.get('AZURE_SUBSCRIPTION_KEY', "AzureMapsSubscriptionKey")) + ) + assert self.client is not None + + @MapsRoutePreparer() + @recorded_by_proxy + def test_get_route_directions(self): + result = self.client.get_route_directions(route_points=[(52.50931,13.42936), (52.50274,13.43872)]) + assert len(result.routes) > 0 + top_answer = result.routes[0] + assert top_answer.summary.length_in_meters == 1147 + assert len(top_answer.legs) > 0 + assert len(top_answer.legs[0].points) > 0 + + # cSpell:ignore CEST + @MapsRoutePreparer() + @recorded_by_proxy + def test_get_route_range(self): + result = self.client.get_route_range(coordinates=(50.97452,5.86605), time_budget_in_sec=6000) + top_answer = result.reachable_range + assert top_answer.center.latitude == 50.97452 + assert top_answer.center.longitude == 5.86605 + assert len(top_answer.boundary) > 0 + assert top_answer.boundary[0].latitude > top_answer.center.latitude + assert top_answer.boundary[0].longitude < top_answer.center.longitude + + @MapsRoutePreparer() + @recorded_by_proxy + def get_route_matrix(self): + request_obj = { + "origins": { + "type": "MultiPoint", + "coordinates": [ + [ + 4.85106, + 52.36006 + ], + [ + 4.85056, + 52.36187 + ] + ] + }, + "destinations": { + "type": "MultiPoint", + "coordinates": [ + [ + 4.85003, + 52.36241 + ], + [ + 13.42937, + 52.50931 + ] + ] + } + } + result = self.client.get_route_matrix(request_obj) + assert len(result.matrix) > 0 + top_answer = result.matrix[0][0] + assert top_answer.response.summary.length_in_meters == 495 diff --git a/sdk/maps/ci.yml b/sdk/maps/ci.yml index b186eb810cb3..08a1f791cce6 100644 --- a/sdk/maps/ci.yml +++ b/sdk/maps/ci.yml @@ -28,7 +28,6 @@ extends: parameters: ServiceDirectory: maps TestProxy: true - TestTimeoutInMinutes: 120 Artifacts: - name: azure-mgmt-maps safeName: azuremgmtmaps @@ -38,4 +37,5 @@ extends: safeName: azuremapsgeolocation - name: azure-maps-render safeName: azuremapsrender - + - name: azure-maps-route + safeName: azuremapsroute diff --git a/sdk/maps/test-resources.json b/sdk/maps/test-resources.json index cf31c5e5a822..c0693fc30cf6 100644 --- a/sdk/maps/test-resources.json +++ b/sdk/maps/test-resources.json @@ -101,4 +101,4 @@ "value": "[resourceGroup().Name]" } } -} \ No newline at end of file +}