次の方法で共有


Python REST SDK 開発者ガイド (プレビュー)

Azure Maps Python SDK は、Python アプリケーションやライブラリと統合して、マップ関連の場所に対応するアプリケーションを構築できます。 Azure Maps Python SDK には、検索、ルート、レンダリング、位置情報の API が含まれています。 これらの API は、アドレスの検索、異なる座標間のルーティング、特定の IP アドレスの地理的位置の取得などの操作をサポートします。

前提条件

ヒント

Azure Maps アカウントはプログラムで作成できます。Azure CLI を使用した例を次に示します。

az maps account create --kind "Gen2" --account-name "myMapAccountName" --resource-group "<resource group>" --sku "G2"

Python プロジェクトを作成する

次の例は、Python で demo という名前のコンソール プログラムを作成する方法を示しています。

mkdir mapsDemo 
cd mapsDemo 
New-Item demo.py 

必要な Python パッケージをインストールする

Azure Maps 内の各サービスは、独自のパッケージに含まれています。 Azure Maps Python SDK を使用する場合は、必要なサービスのパッケージのみをインストールできます。

ここでは、Azure Maps Search パッケージをインストールします。 まだパブリック プレビュー段階であるため、--pre フラグを追加する必要があります。

pip install azure-maps-search --pre 

Azure Maps サービス

Azure Maps Python SDK では、Python バージョン 3.8 以降がサポートされています。 今後の Python バージョンの詳細については、Azure SDK for Python バージョンのサポート ポリシーを参照してください。

[サービス名] PyPi パッケージ サンプル
検索する azure-maps-search 検索サンプル
Route azure-maps-route  ルート サンプル
レンダリング azure-maps-render レンダリング サンプル
位置情報 azure-maps-geolocation 位置情報サンプル

MapsSearchClient の作成と認証

Azure Maps Search API にアクセスするために使用される MapsSearchClient オブジェクトを作成するときに、認証用の credential オブジェクトが必要になります。 認証には、Microsoft Entra 資格情報または Azure サブスクリプション キーを使用できます。 認証の詳細については、「Azure Maps による認証」を参照してください。

ヒント

MapsSearchClient は、Azure Maps の検索ライブラリを使用する開発者向けのプライマリ インターフェイスです。 使用可能な検索方法の詳細については、Azure Maps の検索パッケージ クライアント ライブラリに関するページを参照してください。

Microsoft Entra 資格情報の使用

Azure ID パッケージを使用して、Microsoft Entra ID で認証することもできます。 DefaultAzureCredential プロバイダーを使用するには、Azure ID クライアント パッケージをインストールする必要があります。

pip install azure-identity 

新しい Microsoft Entra アプリケーションを登録し、サービス プリンシパルに必要なロールを割り当てることによって Azure Maps へのアクセス権を付与する必要があります。 詳細については、「Azure 以外のリソースでデーモンをホストする」を参照してください。 アプリケーション (クライアント) ID、ディレクトリ (テナント) ID、クライアント シークレットが返されます。 これらの値をコピーし、安全な場所に保存します。 これらは、次の手順で必要になります。

次に、マップのクライアント ID を指定することによって、使用する Azure Maps アカウントを指定する必要があります。 Azure Maps アカウントのクライアント ID は、Azure Maps アカウントの [認証] セクションにあります。 詳細については「認証の詳細の表示」を参照してください。

次のように、Microsoft Entra アプリケーションのアプリケーション (クライアント) ID、ディレクトリ (テナント) ID、クライアント シークレット、さらに Map リソースのクライアント ID の値を環境変数として設定します。

環境変数 説明
AZURE_CLIENT_ID 登録したアプリケーションのアプリケーション (クライアント) ID
AZURE_CLIENT_SECRET 登録したアプリケーションのクライアント シークレットの値
AZURE_TENANT_ID 登録したアプリケーションのディレクトリ (テナント) ID
MAPS_CLIENT_ID Azure Map アカウントのクライアント ID

次のように、PowerShell で環境変数を作成して、これらの値を保存できるようになりました。

$Env:AZURE_CLIENT_ID="Application (client) ID"
$Env:AZURE_CLIENT_SECRET="your client secret"
$Env:AZURE_TENANT_ID="your Directory (tenant) ID"
$Env:MAPS_CLIENT_ID="your Azure Maps client ID"

環境変数を設定した後、次のようにプログラムでこれらの変数を使用して AzureMapsSearch クライアントをインスタンス化できます。 demo.py という名前のファイルを作成し、次のコードを追加します。

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

credential = DefaultAzureCredential()
maps_client_id = os.getenv("MAPS_CLIENT_ID")
maps_search_client = MapsSearchClient(
    client_id=maps_client_id,
    credential=credential
)

重要

前のコード スニペットで作成されたその他の環境変数は、このコード サンプルでは使用されていませんが、DefaultAzureCredential() で必要になります。 同じ名前付け規則を使用してこれらの環境変数を正しく設定しないと、実行時エラーが発生します。 たとえば、AZURE_CLIENT_ID が見つからないか無効な場合は、InvalidAuthenticationTokenTenant エラーが発生します。

サブスクリプション キー資格情報の使用

Azure Maps サブスクリプション キーを使用して認証できます。 以下のスクリーンショットに示されているように、サブスクリプション キーは Azure Maps アカウントの [認証] セクションに表示されます。

Azure portal の Azure Maps サブスクリプション キーを示すスクリーンショット。

次のように、PowerShell で環境変数を作成して、サブスクリプション キーを保存できるようになりました。

$Env:SUBSCRIPTION_KEY="your subscription key"

環境変数を作成したら、次のようにコードでアクセスできます。 demo.py という名前のファイルを作成し、次のコードを追加します。

import os

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

# Use Azure Maps subscription key authentication
subscription_key = os.getenv("SUBSCRIPTION_KEY")
maps_search_client = MapsSearchClient(
   credential=AzureKeyCredential(subscription_key)
)

住所をジオコーディングする

次のコード スニペットは、単純なコンソール アプリケーションで、指定の住所の経度と緯度の座標を取得する方法を示します。 この例では、サブスクリプション キーの資格情報を使用して MapsSearchClient を認証します。 demo.pyの場合:

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()

このサンプル コードでは、Azure Maps サブスクリプション キーを使用して AzureKeyCredential をインスタンス化した後、それを使用して MapsSearchClient オブジェクトをインスタンス化します。 MapsSearchClient によって提供されるメソッドによって、要求が Azure Maps REST エンドポイントに転送されます。 最後に、プログラムでは結果を反復処理し、各結果の座標を出力します。

住所のバッチ ジオコーディング

このサンプルでは、住所のバッチ検索を実行する方法を示します。

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()

座標位置を住所に変換するために 住所の逆引き検索を行う

座標を人間が理解できる番地に変換できます。 このプロセスはリバース ジオコーディングとも呼ばれています。 これは、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()

特定の場所のポリゴンを取得する

このサンプルでは、ポリゴンを検索する方法を示します。

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()

検索とレンダリングでの V1 SDK の使用

Search V1 SDK と Render V1 SDK を使用する方法の詳細については、、Search V1 SDK パッケージ ページと Render V1 SDK パッケージを参照してください。

追加情報

Azure SDK for Python Preview ドキュメントの Azure Maps 検索パッケージ クライアント ライブラリ