跳转到主要内容

Microsoft Azure Maps Search Python客户端库

项目描述

Azure Maps Search Python包客户端库

本包包含Azure Maps服务的Python SDK。有关Azure Maps服务的更多信息,请点击此处

源代码 | API参考文档 | 产品文档

免责声明

Azure SDK Python包对Python 2.7的支持已于2022年1月1日结束。有关更多信息,请参阅https://github.com/Azure/azure-sdk-for-python/issues/20691

入门指南

先决条件

如果您使用 Azure CLI,请将 <resource-group-name><account-name> 替换为您选择的名称,并通过 <sku-name> 参数选择合适的 定价层。有关详细信息,请参阅 此页面

az maps account create --resource-group <resource-group-name> --account-name <account-name> --sku <sku-name>

安装软件包

安装 Azure Maps 服务搜索 SDK。

pip install azure-maps-search

创建和验证 MapsSearchClient

要创建一个客户端对象以访问 Azure Maps 搜索 API,您需要一个 凭据 对象。Azure Maps 搜索客户端也支持两种身份验证方式。

1. 使用订阅密钥凭据进行身份验证

您可以使用您的 Azure Maps 订阅密钥进行身份验证。一旦创建 Azure Maps 订阅密钥,将其值设置为环境变量:AZURE_SUBSCRIPTION_KEY。然后,将 AZURE_SUBSCRIPTION_KEY 作为 credential 参数传递给 AzureKeyCredential 的一个实例。

from azure.core.credentials import AzureKeyCredential
from azure.maps.search import MapsSearchClient

credential = AzureKeyCredential(os.environ.get("AZURE_SUBSCRIPTION_KEY"))

search_client = MapsSearchClient(
    credential=credential,
)

2. 使用 Azure Active Directory 凭据进行身份验证

您可以使用 Azure Active Directory (AAD) 令牌凭据,通过使用 Azure Identity 库 进行身份验证。使用 AAD 进行身份验证需要一些初始设置

设置后,您可以选择从 azure.identity 中使用哪种类型的 凭据。例如,DefaultAzureCredential 可以用于验证客户端

然后,将 AAD 应用程序的客户端 ID、租户 ID 和客户端密钥的值设置为环境变量:AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET

您还需要通过在客户端选项中指定 clientId 来指定您打算使用的 Azure Maps 资源。Azure Maps 资源客户端 ID 可在 Azure Maps 资源的“身份验证”部分找到。请参阅有关如何查找它的 文档

from azure.maps.search import MapsSearchClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
search_client = MapsSearchClient(credential=credential)

关键概念

Azure Maps 搜索客户端库允许您通过使用专用客户端对象与每个组件进行交互。

同步客户端

MapsSearchClient 是使用 Azure Maps 搜索客户端库的 Python 开发人员的主要客户端。一旦初始化了 MapsSearchClient 类,您就可以探索该客户端对象上的方法,以了解您可以访问的 Azure Maps 搜索服务的不同功能。

异步客户端

此库包含一个完全的异步 API,支持 Python 3.5+。要使用它,您必须首先安装异步传输,如 aiohttp。有关更多信息,请参阅 azure-core 文档

当不再需要时,应关闭异步客户端和凭据。这些对象是异步上下文管理器,并定义异步 close 方法。

示例

以下部分提供了一些代码片段,涵盖了 Azure Maps 搜索的一些最常见任务,包括

地址地理编码

您可以使用认证客户端将地址转换为纬度和经度坐标。这个过程也称为地理编码。除了返回坐标外,响应还将返回详细的地址属性,如街道、邮政编码、市政和国家/地区信息。

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def geocode():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_geocoding(query="15127 NE 24th Street, Redmond, WA 98052")
        if result.get('features', False):
            coordinates = result['features'][0]['geometry']['coordinates']
            longitude = coordinates[0]
            latitude = coordinates[1]

            print(longitude, latitude)
        else:
            print("No results")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    geocode()

批量地址地理编码

此示例演示了如何执行批量搜索地址。

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def geocode_batch():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_geocoding_batch({
          "batchItems": [
            {"query": "400 Broad St, Seattle, WA 98109"},
            {"query": "15127 NE 24th Street, Redmond, WA 98052"},
          ],
        },)

        if not result.get('batchItems', False):
            print("No batchItems in geocoding")
            return

        for item in result['batchItems']:
            if not item.get('features', False):
                print(f"No features in item: {item}")
                continue

            coordinates = item['features'][0]['geometry']['coordinates']
            longitude, latitude = coordinates
            print(longitude, latitude)

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    geocode_batch()

获取给定位置的多边形

此示例演示了如何搜索多边形。

import os

from azure.core.exceptions import HttpResponseError
from azure.maps.search import Resolution
from azure.maps.search import BoundaryResultType


subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_polygon():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_polygon(
          coordinates=[-122.204141, 47.61256],
          result_type=BoundaryResultType.LOCALITY,
          resolution=Resolution.SMALL,
        )

        if not result.get('geometry', False):
            print("No geometry found")
            return

        print(result["geometry"])
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_polygon()

进行反向地址搜索,将坐标位置转换为街道地址

您可以翻译坐标为可读的街道地址。这个过程也称为反向地理编码。这通常用于需要消耗GPS数据并在特定坐标点发现地址的应用程序。

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def reverse_geocode():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.search import MapsSearchClient

    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_reverse_geocoding(coordinates=[-122.138679, 47.630356])
        if result.get('features', False):
            props = result['features'][0].get('properties', {})
            if props and props.get('address', False):
                print(props['address'].get('formattedAddress', 'No formatted address found'))
            else:
                print("Address is None")
        else:
            print("No features available")
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")


if __name__ == '__main__':
   reverse_geocode()

批量请求进行反向地理编码

此示例演示了如何批量按给定坐标执行反向搜索。

import os
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
from azure.maps.search import MapsSearchClient

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def reverse_geocode_batch():
    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = maps_search_client.get_reverse_geocoding_batch({
              "batchItems": [
                {"coordinates": [-122.349309, 47.620498]},
                {"coordinates": [-122.138679, 47.630356]},
              ],
            },)

        if result.get('batchItems', False):
            for idx, item in enumerate(result['batchItems']):
                features = item['features']
                if features:
                    props = features[0].get('properties', {})
                    if props and props.get('address', False):
                        print(
                            props['address'].get('formattedAddress', f'No formatted address for item {idx + 1} found'))
                    else:
                        print(f"Address {idx + 1} is None")
                else:
                    print(f"No features available for item {idx + 1}")
        else:
            print("No batch items found")
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")


if __name__ == '__main__':
   reverse_geocode_batch()

故障排除

常规

地图搜索客户端引发在Azure Core中定义的异常。

此列表可用于参考以捕获抛出的异常。要获取异常的具体错误代码,请使用error_code属性,即exception.error_code

日志记录

此库使用标准的logging库进行日志记录。基本HTTP会话信息(URL、标头等)在INFO级别记录。

启用详细DEBUG级别日志记录,包括请求/响应正文和未删除的标头,可以通过客户端的logging_enable参数启用。

import sys
import logging
from azure.maps.search import MapsSearchClient

# Create a logger for the 'azure.maps.search' SDK
logger = logging.getLogger('azure.maps.search')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

同样,logging_enable可以为一个单独的操作启用详细日志记录,即使对于客户端没有启用。

service_client.get_service_stats(logging_enable=True)

其他

仍在遇到问题?如果您遇到任何错误或有建议,请在项目的问题部分提交问题。

下一步

更多示例代码

从我们的地图搜索示例异步版本示例)开始。

在SDK的GitHub存储库中提供了几个Azure Maps Search Python SDK示例。这些示例提供了在处理地图搜索时常见场景的示例代码。

set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"

pip install azure-maps-search --pre

python samples/sample_geocode.py
python sample/sample_geocode_batch.py
python samples/sample_get_polygon.py
python samples/sample_reverse_geocode.py
python samples/sample_reverse_geocode_batch.py

注意:--pre标志是可选的,它是为了在pip install中包括预发布和开发版本。默认情况下,pip只查找稳定版本。

更详细的信息请参阅示例介绍

其他文档

有关Azure Maps Search的更广泛文档,请参阅docs.microsoft.com上的Azure Maps Search文档

贡献

此项目欢迎贡献和建议。大多数贡献都需要您同意贡献者许可协议(CLA),声明您有权并且实际上确实授予我们使用您的贡献的权利。有关详细信息,请访问https://cla.microsoft.com

当您提交拉取请求时,CLA-bot将自动确定您是否需要提供CLA,并相应地装饰PR(例如,标签、注释)。只需遵循机器人提供的说明即可。您只需要在整个使用我们的CLA的存储库中这样做一次。

此项目已采用Microsoft开源行为准则。有关更多信息,请参阅行为准则FAQ或联系opencode@microsoft.com,如有任何其他问题或评论。

发布历史

2.0.0b1 (2024-08-06)

新功能和增强

  • 支持2023-06-01搜索API

  • 地理编码API

    • 引入了get_geocoding方法,用于获取给定地址的经纬度坐标。
    • 引入了 get_geocoding_batch 方法来处理批量地理编码查询,单个请求最多支持100个查询。
  • 反向地理编码API

    • 引入了 get_reverse_geocoding 方法,可以从给定的坐标中获取地址详细信息。
    • 引入了 get_reverse_geocoding_batch 方法来处理批量反向地理编码查询,单个请求最多支持100个查询。
  • 边界API

    • 引入了 get_polygon 方法,可以获取具有指定分辨率和边界结果类型的坐标集的多边形边界。

重大更改

  • 移除的方法
    • 移除了 fuzzy_search 方法。
    • 移除了 search_point_of_interest 方法。
    • 移除了 search_address 方法。
    • 移除了 search_nearby_point_of_interest 方法。
    • 移除了 search_point_of_interest_category 方法。
    • 移除了 search_structured_address 方法。
    • 移除了 get_geometries 方法。
    • 移除了 get_point_of_interest_categories 方法。
    • 移除了 reverse_search_address 方法。
    • 移除了 reverse_search_cross_street_address 方法。
    • 移除了 search_inside_geometry 方法。
    • 移除了 search_along_route 方法。
    • 移除了 fuzzy_search_batch 方法。
    • 移除了 search_address_batch 方法。

1.0.0b3 (2024-05-15)

已修复的bug

  • 修复了反向搜索地址的响应验证错误

其他更改

  • 修复了 README.md 中的反向搜索示例
  • 修复了 Sphinx 错误
  • 修复了 pylint 2.15.8 版本的 pylint 错误

1.0.0b2 (2022-10-11)

其他更改

  • 使用新的测试代理更新了测试
  • 更新了文档字符串

1.0.0b1 (2022-09-06)

  • 初始发布

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

azure-maps-search-2.0.0b1.tar.gz (55.0 kB 查看哈希值)

上传时间

构建分布

azure_maps_search-2.0.0b1-py3-none-any.whl (53.3 kB 查看哈希值)

上传时间 Python 3

支持者:

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面