Utvecklarguide för Python REST SDK (förhandsversion)
Azure Maps Python SDK kan integreras med Python-program och -bibliotek för att skapa kartrelaterade och platsmedvetna program. Azure Maps Python SDK innehåller API:er för sökning, väg, återgivning och geoplats. Dessa API:er stöder åtgärder som att söka efter en adress, dirigera mellan olika koordinater och hämta geo-platsen för en specifik IP-adress.
Förutsättningar
- Azure Maps-konto.
- Prenumerationsnyckel eller annan form av autentisering med Azure Maps.
- Python på 3.8 eller senare. Vi rekommenderar att du använder den senaste versionen. Mer information finns i Supportprincip för Azure SDK för Python-version.
Dricks
Du kan skapa ett Azure Maps-konto programmatiskt. Här är ett exempel med hjälp av Azure CLI:
az maps account create --kind "Gen2" --account-name "myMapAccountName" --resource-group "<resource group>" --sku "G2"
Skapa ett Python-projekt
I följande exempel visas hur du skapar ett konsolprogram med namnet demo
med Python:
mkdir mapsDemo
cd mapsDemo
New-Item demo.py
Installera nödvändiga Python-paket
Varje tjänst i Azure Maps finns i ett eget paket. När du använder Azure Maps Python SDK kan du bara installera paketen för de tjänster du behöver.
Här installerar vi Azure Maps Search-paketet. Eftersom den fortfarande är i offentlig förhandsversion måste du lägga --pre
till flaggan:
pip install azure-maps-search --pre
Azure Maps-tjänster
Azure Maps Python SDK stöder Python version 3.8 eller senare. Mer information om framtida Python-versioner finns i Supportprincip för Azure SDK för Python-version.
Tjänstnamn | PyPi-paket | Prover |
---|---|---|
Sök | azure-maps-search | sökexempel |
Rutt | azure-maps-route | vägexempel |
Rendera | azure-maps-render | rendera exempel |
Geoplats | azure-maps-geolocation | geoplatsexempel |
Skapa och autentisera en MapsSearchClient
Du behöver ett credential
objekt för autentisering när du skapar objektet MapsSearchClient
som används för att komma åt Api:erna för Azure Maps-sökning. Du kan använda antingen en Microsoft Entra-autentiseringsuppgift eller en Azure-prenumerationsnyckel för att autentisera. Mer information om autentisering finns i Autentisering med Azure Maps.
Dricks
MapsSearchClient
är det primära gränssnittet för utvecklare som använder Azure Maps-sökbiblioteket. Mer information om tillgängliga sökmetoder finns i Azure Maps Search-paketklientbiblioteket .
Använda en Microsoft Entra-autentiseringsuppgift
Du kan autentisera med Microsoft Entra-ID med hjälp av Azure Identity-paketet. Om du vill använda StandardAzureCredential-providern måste du installera Azure Identity-klientpaketet:
pip install azure-identity
Du måste registrera det nya Microsoft Entra-programmet och bevilja åtkomst till Azure Maps genom att tilldela den roll som krävs till tjänstens huvudnamn. Mer information finns i Host a daemon on non-Azure resources (Värd för en daemon för icke-Azure-resurser). Program-ID(klient)-ID, ett katalog-ID (klient)-ID och en klienthemlighet returneras. Kopiera dessa värden och lagra dem på en säker plats. Du behöver dem i följande steg.
Därefter måste du ange det Azure Maps-konto som du tänker använda genom att ange kartornas klient-ID. Klient-ID:t för Azure Maps-kontot finns i avsnitten Autentisering i Azure Maps-kontot. Mer information finns i Visa autentiseringsinformation.
Ange värdena för program-ID,katalog-ID (klient)-ID och klienthemlighet för ditt Microsoft Entra-program och mappningsresursens klient-ID som miljövariabler:
Miljövariabel | beskrivning |
---|---|
AZURE_CLIENT_ID | Program-ID (klient) i ditt registrerade program |
AZURE_CLIENT_SECRET | Värdet för klienthemligheten i ditt registrerade program |
AZURE_TENANT_ID | Katalog-ID (klientorganisation) i ditt registrerade program |
MAPS_CLIENT_ID | Klient-ID:t i ditt Azure Map-konto |
Nu kan du skapa miljövariabler i PowerShell för att lagra följande värden:
$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"
När du har konfigurerat miljövariablerna kan du använda dem i programmet för att instansiera AzureMapsSearch
klienten. Skapa en fil med namnet demo.py och lägg till följande kod:
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
)
Viktigt!
De andra miljövariablerna som skapades i föregående kodfragment, men som inte används i kodexemplet, krävs av DefaultAzureCredential()
. Om du inte ställer in dessa miljövariabler korrekt får du körningsfel med samma namngivningskonventioner. Om du AZURE_CLIENT_ID
till exempel saknar eller är ogiltig får du ett InvalidAuthenticationTokenTenant
fel.
Använda en prenumerationsnyckelautentiseringsuppgifter
Du kan autentisera med din Azure Maps-prenumerationsnyckel. Din prenumerationsnyckel finns i avsnittet Autentisering i Azure Maps-kontot enligt följande skärmbild:
Nu kan du skapa miljövariabler i PowerShell för att lagra prenumerationsnyckeln:
$Env:SUBSCRIPTION_KEY="your subscription key"
När miljövariabeln har skapats kan du komma åt den i koden. Skapa en fil med namnet demo.py och lägg till följande kod:
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)
)
Geokoda en adress
Följande kodfragment visar hur du i ett enkelt konsolprogram hämtar longitud- och latitudkoordinater för en viss adress. I det här exemplet används autentiseringsuppgifter för prenumerationsnycklar för att autentisera MapsSearchClient. I 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()
Den här exempelkoden instansierar AzureKeyCredential
med Azure Maps-prenumerationsnyckeln och använder den sedan för att instansiera MapsSearchClient
objektet. Metoderna som tillhandahålls genom MapsSearchClient
att vidarebefordra begäran till Azure Maps REST-slutpunkter. I slutändan itererar programmet genom resultaten och skriver ut koordinaterna för varje resultat.
Batch-geokodadresser
Det här exemplet visar hur du utför en batchsökningsadress:
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()
Gör en omvänd adresssökning för att översätta koordinatplatsen till gatuadressen
Du kan översätta koordinater till gatuadresser som kan läsas av människor. Den här processen kallas även omvänd geokodning. Detta används ofta för program som använder GPS-flöden och vill identifiera adresser vid specifika koordinatpunkter.
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()
Batch-begäran om omvänd geokodning
Det här exemplet visar hur du utför omvänd sökning med angivna koordinater i batch.
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()
Hämta polygoner för en viss plats
Det här exemplet visar hur du söker i polygoner.
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()
Använda V1-SDK:er för sökning och återgivning
Mer information finns på sidan Search V1 SDK package (Sök V1 SDK-paket) och Rendera V1 SDK-paket för att få mer information.
Ytterligare information
Azure Maps Search-paketklientbiblioteket i dokumentationen för Förhandsversionen av Azure SDK för Python.