Azure 地圖服務適用于 Python 的搜尋套件用戶端程式庫 - 1.0.0b2 版
此套件包含適用于搜尋Azure 地圖服務服務的 Python SDK。 在這裡深入瞭解Azure 地圖服務服務
免責聲明
Python 2.7 的 Azure SDK Python 套件支援已于 2022 年 1 月 1 日結束。 如需詳細資訊和問題,請參閱 https://github.com/Azure/azure-sdk-for-python/issues/20691
開始使用
Prerequisites
- 需要 Python 3.6 或更新版本才能使用此套件。
- Azure 訂用帳戶和Azure 地圖服務帳戶。
- 已部署的地圖服務資源。 您可以透過 Azure 入口網站或 AzureCLI建立資源。
如果您使用 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 地圖服務 服務搜尋 SDK。
pip install azure-maps-search
建立及驗證 MapsSearchClient
若要建立用戶端物件來存取Azure 地圖服務搜尋 API,您需要認證物件。 Azure 地圖服務搜尋用戶端也支援兩種方式進行驗證。
1.使用訂用帳戶金鑰認證進行驗證
您可以使用Azure 地圖服務訂用帳戶金鑰進行驗證。
建立Azure 地圖服務訂用帳戶金鑰之後,請將金鑰的值設定為環境變數: AZURE_SUBSCRIPTION_KEY
。
然後將 作為 credential
參數傳遞 AZURE_SUBSCRIPTION_KEY
至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 身分識別連結庫向 Azure Active Directory (AAD) 權杖認證進行驗證。 使用 AAD 進行驗證需要一些初始設定:
- 安裝 azure-identity
- 註冊 新的 AAD 應用程式
- 將適當的角色指派給服務主體,以授與對Azure 地圖服務的存取權。 請參閱 管理驗證頁面。
安裝之後,您可以選擇 要使用的認證azure.identity
類型。
例如, DefaultAzureCredential 可用來驗證用戶端:
接下來,將 AAD 應用程式的用戶端識別碼、租使用者識別碼和用戶端密碼的值設定為環境變數: AZURE_CLIENT_ID
、、、 AZURE_TENANT_ID
AZURE_CLIENT_SECRET
您也必須在用戶端選項中指定 clientId
,以指定您想要使用的Azure 地圖服務資源。 Azure 地圖服務資源用戶端識別碼可在Azure 地圖服務資源的 [驗證] 區段中找到。 請參閱有關如何尋找的檔。
from azure.maps.search import MapsSearchClient
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
search_client = MapsSearchClient(credential=credential)
重要概念
適用于 Python 的Azure 地圖服務搜尋用戶端程式庫可讓您透過使用專用用戶端物件,與每個元件互動。
同步處理用戶端
MapsSearchClient
是開發人員使用適用于 Python 的 Azure 地圖服務 搜尋用戶端程式庫的主要用戶端。
初始化 MapsSearchClient
類別之後,您可以探索此用戶端物件上的方法,以瞭解您可以存取之Azure 地圖服務 搜尋服務的不同功能。
非同步用戶端
此程式庫包含 Python 3.5+ 上支援的完整非同步 API。 若要使用它,您必須先安裝非同步傳輸,例如 aioHTTP。 如需詳細資訊 ,請參閱 azure 核心檔 。
不再需要非同步用戶端和認證時,應該關閉它們。 這些物件是非同步內容管理員,並定義非同步 close
方法。
範例
下列各節提供數個程式碼片段,涵蓋一些最常見的Azure 地圖服務搜尋工作,包括:
要求位址的緯度和經度座標
您可以使用已驗證的用戶端,將位址轉換成緯度和經度座標。 此流程也稱為地理編碼。 除了傳回座標以外,回應也會傳回詳細的地址屬性,例如街道、郵遞區號、自治區和國家/區域資訊。
from azure.maps.search import MapsSearchClient
search_result = client.search_address("400 Broad, Seattle");
搜尋位址或景點
您可以使用模糊搜尋來搜尋位址或 (POI) 的景點。 下列範例示範如何搜尋 pizza
特定國家/地區 (France
的範圍,在此範例中) 。
from azure.maps.search import MapsSearchClient
fuzzy_search_result = client.fuzzy_search(query: "pizza", country_filter: "fr" );
result_address = fuzzy_search_result.results[0].address
建立反向位址搜尋,將座標位置轉譯為街地道址
您可以將座標轉譯成人類可讀取的街地道址。 此程式也稱為反向地理編碼。 這通常用於取用 GPS 摘要,並想要在特定座標點探索位址的應用程式。
from azure.maps.search import MapsSearchClient
coordinates=(47.60323, -122.33028)
reverse_search_result = client.reverse_search_address(coordinates=coordinates);
result_summary = reverse_search_result.summary
將座標位置轉譯為人類可理解的交叉街
使用搜尋地址反向交叉路口 API,將座標位置轉譯成人類可理解的交叉路口。 在追蹤從裝置或資產接收 GPS 摘要的應用程式,並想要知道座標位置時,最常使用此功能。
from azure.maps.search import MapsSearchClient
coordinates=(47.60323, -122.33028)
reverse_search_result = client.reverse_search_cross_street_address(coordinates=coordinates);
result_address = reverse_search_result.results[0].address
使用 param 和 batchid 取得非同步模糊搜尋批次
此範例示範如何使用非同步批次方法,依位置和 lat/lon 執行模糊搜尋。 此函式同時接受 search_queries
和 batch_id
並傳 AsyncLRO
回 物件。 batch_id
這裡可用來擷取過去 14 天之後的 LRO 物件。
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
async with maps_search_client:
result = await maps_search_client.begin_fuzzy_search_batch(
search_queries=[
"350 5th Ave, New York, NY 10118&limit=1",
"400 Broad St, Seattle, WA 98109&limit=6"
]
)
batch_id = result.batch_id
方法 begin_fuzzy_search_batch()
也會接受 batch_id
做為 參數。 batch_id
這裡可用來擷取過去 14 天之後的 LRO 物件。
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
async with maps_search_client:
result = await maps_search_client.begin_fuzzy_search_batch(
batch_id=batch_id
)
result = result.response
無法取得模糊搜尋批次同步處理
此範例示範如何檢查搜尋fuzzy_search_batch是否有失敗。
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
result = maps_search_client.fuzzy_search_batch(
search_queries=[
"350 5th Ave, New York, NY 10118&limit=1",
"400 Broad St, Seattle, WA 98109&lim"
]
)
for item in result.items:
count = 0
if item.response.error is not None:
count = count+1
print(f"Error: {item.response.error.message}")
print(f"There are total of {count} search queries failed.")
在 Geometry 內搜尋
此範例示範如何使用 GeoJson 物件,在幾何內部執行搜尋,例如 pizza
和多個不同的幾何作為輸入。
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
geo_json_obj1 = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[
[-122.143035,47.653536],
[-122.187164,47.617556],
[-122.114981,47.570599],
[-122.132756,47.654009],
[-122.143035,47.653536]
]]
},
"properties": {}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-122.126986,47.639754]
},
"properties": {
"subType": "Circle",
"radius": 100
}
}
]
}
result1 = maps_search_client.search_inside_geometry(
query="pizza",
geometry=geo_json_obj1
)
print("Search inside geometry with standard GeoJson object as input, FeatureCollection:")
print(result1)
使用搜尋的存在程式庫
此範例示範如何使用其他現有的套件,例如 shapely
,依指定的目標在幾何內執行搜尋,例如 pizza
。
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
from shapely.geometry import Polygon
geo_interface_obj = Polygon([
[-122.43576049804686, 37.7524152343544],
[-122.43301391601562, 37.70660472542312],
[-122.36434936523438, 37.712059855877314],
[-122.43576049804686, 37.7524152343544]
])
result3 = maps_search_client.search_inside_geometry(
query="pizza",
geometry=geo_interface_obj
)
print("Search inside geometry with Polygon from third party library `shapely` with geo_interface as result 3:")
print(result2)
疑難排解
一般
地圖搜尋用戶端會引發 Azure Core中定義的例外狀況。
此清單可用於參考,以攔截擲回的例外狀況。 若要取得例外狀況的特定錯誤碼,請使用 error_code
屬性,也就是 exception.error_code
。
記錄
此程式庫會使用標準記錄程式庫進行 記錄 。 HTTP 會話的基本資訊 (URL、標頭等。) 會記錄在 INFO 層級。
您可以在具有 引數的用戶端 logging_enable
上啟用詳細的 DEBUG 層級記錄,包括要求/回應主體和未回應標頭:
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 地圖服務搜尋 Python SDK 範例可供您使用。 這些範例提供使用地圖服務搜尋時常遇到的其他案例範例程式碼
set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"
pip install azure-maps-search --pre
python samples/sample_authentication.py
python sample/sample_fuzzy_search.py
python samples/sample_get_point_of_interest_categories.py
python samples/sample_reverse_search_address.py
python samples/sample_reverse_search_cross_street_address.py
python samples/sample_search_nearby_point_of_interest.py
python samples/sample_search_point_of_interest_category.py
python samples/sample_search_point_of_interest.py
python samples/sample_search_structured_address.py
注意:
--pre
您可以選擇性地新增 旗標,其包含 的pip install
發行前版本和開發版本。 根據預設,pip
只會尋找穩定版本。
如需詳細資訊,請參閱 範例簡介
其他文件
如需Azure 地圖服務搜尋的詳細資訊檔,請參閱Azure 地圖服務搜尋檔docs.microsoft.com。
參與
此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資料,請前往 https://cla.microsoft.com 。
當您提交提取要求時,CLA Bot 會自動判斷您是否需要提供 CLA,並適當地裝飾 PR (例如標籤、註解)。 請遵循 bot 提供的指示。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。
此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com。
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應