Skip to content

Commit 229a635

Browse files
authored
Update how-to-dev-guide-py-sdk.md
1 parent afd1baa commit 229a635

File tree

1 file changed

+172
-165
lines changed

1 file changed

+172
-165
lines changed

articles/azure-maps/how-to-dev-guide-py-sdk.md

Lines changed: 172 additions & 165 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ The Azure Maps Python SDK can be integrated with Python applications and librari
1919

2020
- [Azure Maps account].
2121
- [Subscription key] or other form of [Authentication with Azure Maps].
22-
- Python on 3.7 or later. It's recommended to use the [latest release]. For more information, see [Azure SDK for Python version support policy].
22+
- Python on 3.8 or later. It's recommended to use the [latest release]. For more information, see [Azure SDK for Python version support policy].
2323

2424
> [!TIP]
2525
> You can create an Azure Maps account programmatically, Here's an example using the Azure CLI:
@@ -50,7 +50,7 @@ pip install azure-maps-search --pre
5050

5151
### Azure Maps services
5252

53-
Azure Maps Python SDK supports Python version 3.7 or later. For more information on future Python versions, see [Azure SDK for Python version support policy].
53+
Azure Maps Python SDK supports Python version 3.8 or later. For more information on future Python versions, see [Azure SDK for Python version support policy].
5454

5555
| Service name  | PyPi package  | Samples  |
5656
|----------------------------|-------------------------|--------------|
@@ -143,210 +143,217 @@ maps_search_client = MapsSearchClient(
143143
)
144144
```
145145

146-
## Fuzzy Search an Entity
146+
## Geocode an address
147147

148-
The following code snippet demonstrates how, in a simple console application, to import the `Azure.Maps.Search` package and perform a fuzzy search on “Starbucks” near Seattle. This example uses subscription key credentials to authenticate MapsSearchClient. In `demo.py`:
148+
The following code snippet demonstrates how, in a simple console application, to obtain longitude and latitude coordinates for a given address. This example uses subscription key credentials to authenticate MapsSearchClient. In `demo.py`:
149149

150150
```Python
151-
import os
152-
from azure.core.credentials import AzureKeyCredential
153-
from azure.maps.search import MapsSearchClient
151+
import os
154152

155-
def fuzzy_search():
156-
    # Use Azure Maps subscription key authentication
157-
subscription_key = os.getenv("SUBSCRIPTION_KEY")
158-
    maps_search_client = MapsSearchClient(
159-
        credential=AzureKeyCredential(subscription_key)
160-
    )
161-
    result = maps_search_client.fuzzy_search(
162-
        query="Starbucks",
163-
        coordinates=(47.61010, -122.34255)
164-
    )
165-
166-
    # Print the search results
167-
if len(result.results) > 0:
168-
print("Starbucks search result nearby Seattle:")
169-
for result_item in result.results:
170-
print(f"* {result_item.address.street_number } {result_item.address.street_name }")
171-
print(f" {result_item.address.municipality } {result_item.address.country_code } {result_item.address.postal_code }")
172-
print(f" Coordinate: {result_item.position.lat}, {result_item.position.lon}")
173-
174-
if __name__ == '__main__':
175-
    fuzzy_search()
176-
```
153+
from azure.core.exceptions import HttpResponseError
177154

178-
This sample code instantiates `AzureKeyCredential` with the Azure Maps subscription key, then uses it to instantiate the `MapsSearchClient` object. The methods provided by `MapsSearchClient` forward the request to the Azure Maps REST endpoints. In the end, the program iterates through the results and prints the address and coordinates for each result.
155+
subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")
179156

180-
After finishing the program, run `python demo.py` from the project folder in PowerShell:
157+
def geocode():
158+
from azure.core.credentials import AzureKeyCredential
159+
from azure.maps.search import MapsSearchClient
181160

182-
```powershell
183-
python demo.py
184-
```
161+
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
162+
try:
163+
result = maps_search_client.get_geocoding(query="15127 NE 24th Street, Redmond, WA 98052")
164+
if result.get('features', False):
165+
coordinates = result['features'][0]['geometry']['coordinates']
166+
longitude = coordinates[0]
167+
latitude = coordinates[1]
168+
169+
print(longitude, latitude)
170+
else:
171+
print("No results")
185172

186-
You should see a list of Starbucks address and coordinate results:
187-
188-
```text
189-
* 1912 Pike Place
190-
Seattle US 98101
191-
Coordinate: 47.61016, -122.34248
192-
* 2118 Westlake Avenue
193-
Seattle US 98121
194-
Coordinate: 47.61731, -122.33782
195-
* 2601 Elliott Avenue
196-
Seattle US 98121
197-
Coordinate: 47.61426, -122.35261
198-
* 1730 Howell Street
199-
Seattle US 98101
200-
Coordinate: 47.61716, -122.3298
201-
* 220 1st Avenue South
202-
Seattle US 98104
203-
Coordinate: 47.60027, -122.3338
204-
* 400 Occidental Avenue South
205-
Seattle US 98104
206-
Coordinate: 47.5991, -122.33278
207-
* 1600 East Olive Way
208-
Seattle US 98102
209-
Coordinate: 47.61948, -122.32505
210-
* 500 Mercer Street
211-
Seattle US 98109
212-
Coordinate: 47.62501, -122.34687
213-
* 505 5Th Ave S
214-
Seattle US 98104
215-
Coordinate: 47.59768, -122.32849
216-
* 425 Queen Anne Avenue North
217-
Seattle US 98109
218-
Coordinate: 47.62301, -122.3571
173+
except HttpResponseError as exception:
174+
if exception.error is not None:
175+
print(f"Error Code: {exception.error.code}")
176+
print(f"Message: {exception.error.message}")
177+
178+
if __name__ == '__main__':
179+
geocode()
219180
```
220181

221-
## Search an Address
182+
This sample code instantiates `AzureKeyCredential` with the Azure Maps subscription key, then uses it to instantiate the `MapsSearchClient` object. The methods provided by `MapsSearchClient` forward the request to the Azure Maps REST endpoints. In the end, the program iterates through the results and prints the coordinates for each result.
183+
222184

223-
Call the `SearchAddress` method to get the coordinate of an address. Modify the Main program from the sample as follows:
185+
## Batch geocode addresses
186+
187+
This sample demonstrates how to perform batch search address:
224188

225189
```Python
226190
import os
227-
from azure.core.credentials import AzureKeyCredential
228-
from azure.maps.search import MapsSearchClient
229191

230-
def search_address():
231-
subscription_key = os.getenv("SUBSCRIPTION_KEY")
192+
from azure.core.exceptions import HttpResponseError
232193

233-
    maps_search_client = MapsSearchClient(
234-
credential=AzureKeyCredential(subscription_key)
235-
)
194+
subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")
236195

237-
  result = maps_search_client.search_address(
238-
query="1301 Alaskan Way, Seattle, WA 98101, US"
239-
)
240-
241-
# Print reuslts if any
242-
if len(result.results) > 0:
243-
    print(f"Coordinate: {result.results[0].position.lat}, {result.results[0].position.lon}")
244-
else:
245-
print("No address found")
196+
def geocode_batch():
197+
from azure.core.credentials import AzureKeyCredential
198+
from azure.maps.search import MapsSearchClient
246199

247-
if __name__ == '__main__':
248-
    search_address()
249-
```
200+
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
201+
try:
202+
result = maps_search_client.get_geocoding_batch({
203+
"batchItems": [
204+
{"query": "400 Broad St, Seattle, WA 98109"},
205+
{"query": "15127 NE 24th Street, Redmond, WA 98052"},
206+
],
207+
},)
250208

251-
The `SearchAddress` method returns results ordered by confidence score and prints the coordinates of the first result.
209+
if not result.get('batchItems', False):
210+
print("No batchItems in geocoding")
211+
return
252212

253-
## Batch reverse search
213+
for item in result['batchItems']:
214+
if not item.get('features', False):
215+
print(f"No features in item: {item}")
216+
continue
254217

255-
Azure Maps Search also provides some batch query methods. These methods return long-running operations (LRO) objects. The requests might not return all the results immediately, so users can choose to wait until completion or query the result periodically. The following examples demonstrate how to call the batched reverse search method.
218+
coordinates = item['features'][0]['geometry']['coordinates']
219+
longitude, latitude = coordinates
220+
print(longitude, latitude)
256221

257-
Since these return LRO objects, you need the `asyncio` method included in the `aiohttp` package:
222+
except HttpResponseError as exception:
223+
if exception.error is not None:
224+
print(f"Error Code: {exception.error.code}")
225+
print(f"Message: {exception.error.message}")
258226

259-
```powershell
260-
pip install aiohttp
227+
if __name__ == '__main__':
228+
geocode_batch()
261229
```
262230

263-
```Python
264-
import asyncio
231+
232+
## Make a Reverse Address Search to translate coordinate location to street address
233+
234+
You can translate coordinates into human-readable street addresses. This process is also called reverse geocoding. This is often used for applications that consume GPS feeds and want to discover addresses at specific coordinate points.
235+
236+
```python
265237
import os
266-
from azure.core.credentials import AzureKeyCredential
267-
from azure.maps.search.aio import MapsSearchClient
268238

269-
async def begin_reverse_search_address_batch():
270-
subscription_key = os.getenv("SUBSCRIPTION_KEY")
239+
from azure.core.exceptions import HttpResponseError
240+
241+
subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")
271242

272-
    maps_search_client = MapsSearchClient(AzureKeyCredential(subscription_key))
243+
def reverse_geocode():
244+
from azure.core.credentials import AzureKeyCredential
245+
from azure.maps.search import MapsSearchClient
246+
247+
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
248+
try:
249+
result = maps_search_client.get_reverse_geocoding(coordinates=[-122.138679, 47.630356])
250+
if result.get('features', False):
251+
props = result['features'][0].get('properties', {})
252+
if props and props.get('address', False):
253+
print(props['address'].get('formattedAddress', 'No formatted address found'))
254+
else:
255+
print("Address is None")
256+
else:
257+
print("No features available")
258+
except HttpResponseError as exception:
259+
if exception.error is not None:
260+
print(f"Error Code: {exception.error.code}")
261+
print(f"Message: {exception.error.message}")
273262

274-
    async with maps_search_client:
275-
        result = await maps_search_client.begin_reverse_search_address_batch(
276-
            search_queries = [
277-
                "148.858561,2.294911",
278-
                "47.639765,-122.127896&radius=5000",
279-
                "47.61559,-122.33817&radius=5000",
280-
            ]
281-
        )
282-
    print(f"Batch_id: {result.batch_id}")
283263

284264
if __name__ == '__main__':
285-
# Special handle for Windows platform
286-
if os.name == 'nt':
287-
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
288-
    asyncio.run(begin_reverse_search_address_batch())
265+
reverse_geocode()
289266
```
290267

291-
In the above example, three queries are passed to the batched reverse search request. To get the LRO results, the request creates a batch request with a batch ID as result that can be used to fetch batch response later. The LRO results are cached on the server side for 14 days.
292268

293-
The following example demonstrates the process of calling the batch ID and retrieving the operation results of the batch request:
269+
## Batch request for reverse geocoding
270+
271+
This sample demonstrates how to perform reverse search by given coordinates in batch.
294272

295273
```python
296-
import asyncio
297274
import os
298275
from azure.core.credentials import AzureKeyCredential
299-
from azure.maps.search.aio import MapsSearchClient
300-
301-
async def begin_reverse_search_address_batch():
302-
subscription_key = os.getenv("SUBSCRIPTION_KEY")
303-
304-
    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
305-
306-
    async with maps_search_client:
307-
        result = await maps_search_client.begin_reverse_search_address_batch(
308-
            search_queries = [
309-
                "148.858561,2.294911",
310-
                "47.639765,-122.127896&radius=5000",
311-
                "47.61559,-122.33817&radius=5000",
312-
            ]
313-
        )
314-
    return result
315-
316-
async def begin_reverse_search_address_batch_with_id(batch_id):
317-
    subscription_key = os.getenv("SUBSCRIPTION_KEY")
318-
    maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
319-
    async with maps_search_client:
320-
        result = await maps_search_client.begin_reverse_search_address_batch(
321-
            batch_id=batch_id,
322-
        )
323-
324-
    responses = result._polling_method._initial_response.context.get('deserialized_data')
325-
    summary = responses['summary']
326-
327-
# Print Batch results
328-
    idx = 1
329-
print(f"Total Batch Requests: {summary['totalRequests']}, Total Successful Results: {summary['successfulRequests']}")
330-
for items in responses.get('batchItems'):
331-
if items['statusCode'] == 200:
332-
print(f"Request {idx} result:")
333-
for address in items['response']['addresses']:
334-
print(f" {address['address']['freeformAddress']}")
276+
from azure.core.exceptions import HttpResponseError
277+
from azure.maps.search import MapsSearchClient
278+
279+
subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")
280+
281+
def reverse_geocode_batch():
282+
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
283+
try:
284+
result = maps_search_client.get_reverse_geocoding_batch({
285+
"batchItems": [
286+
{"coordinates": [-122.349309, 47.620498]},
287+
{"coordinates": [-122.138679, 47.630356]},
288+
],
289+
},)
290+
291+
if result.get('batchItems', False):
292+
for idx, item in enumerate(result['batchItems']):
293+
features = item['features']
294+
if features:
295+
props = features[0].get('properties', {})
296+
if props and props.get('address', False):
297+
print(
298+
props['address'].get('formattedAddress', f'No formatted address for item {idx + 1} found'))
299+
else:
300+
print(f"Address {idx + 1} is None")
301+
else:
302+
print(f"No features available for item {idx + 1}")
335303
else:
336-
print(f"Error in request {idx}: {items['response']['error']['message']}")
337-
idx += 1
338-
339-
async def main():
340-
    result = await begin_reverse_search_address_batch()
341-
    await begin_reverse_search_address_batch_with_id(result.batch_id)
342-
343-
if __name__ == '__main__':
344-
# Special handle for Windows platform
345-
if os.name == 'nt':
346-
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
347-
    asyncio.run(main())
304+
print("No batch items found")
305+
except HttpResponseError as exception:
306+
if exception.error is not None:
307+
print(f"Error Code: {exception.error.code}")
308+
print(f"Message: {exception.error.message}")
309+
310+
311+
if __name__ == '__main__':
312+
reverse_geocode_batch()
313+
```
314+
315+
316+
## Get polygons for a given location
317+
318+
This sample demonstrates how to search polygons.
319+
320+
```python
321+
import os
322+
323+
from azure.core.exceptions import HttpResponseError
324+
from azure.maps.search import Resolution
325+
from azure.maps.search import BoundaryResultType
326+
327+
328+
subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")
329+
330+
def get_polygon():
331+
from azure.core.credentials import AzureKeyCredential
332+
from azure.maps.search import MapsSearchClient
333+
334+
maps_search_client = MapsSearchClient(credential=AzureKeyCredential(subscription_key))
335+
try:
336+
result = maps_search_client.get_polygon(
337+
coordinates=[-122.204141, 47.61256],
338+
result_type=BoundaryResultType.LOCALITY,
339+
resolution=Resolution.SMALL,
340+
)
341+
342+
if not result.get('geometry', False):
343+
print("No geometry found")
344+
return
345+
346+
print(result["geometry"])
347+
except HttpResponseError as exception:
348+
if exception.error is not None:
349+
print(f"Error Code: {exception.error.code}")
350+
print(f"Message: {exception.error.message}")
351+
352+
if __name__ == '__main__':
353+
get_polygon()
348354
```
349355

356+
350357
## Additional information
351358

352359
The [Azure Maps Search package client library] in the *Azure SDK for Python Preview* documentation.

0 commit comments

Comments
 (0)