azure-maps-search-dotnet
microsoft/skills
將 Azure Maps 基於位置的服務整合到 .NET 應用程式中,以支援地理編碼、路徑規劃、地圖渲染、地理定位和天氣資料等功能。
...展開全部Azure Maps (.NET)
Azure Maps 用於 .NET 的 SDK,提供基於位置的服務:地理編碼、路線規劃、地圖渲染、地理定位和天氣。
安裝
# 搜尋(地理編碼、反向地理編碼)
dotnet add package Azure.Maps.Search --prerelease
# 路線規劃(路線指引、路線矩陣)
dotnet add package Azure.Maps.Routing --prerelease
# 渲染(地圖瓦片、靜態影象)
dotnet add package Azure.Maps.Rendering --prerelease
# 地理定位(IP 地址到地理位置)
dotnet add package Azure.Maps.Geolocation --prerelease
# 天氣
dotnet add package Azure.Maps.Weather --prerelease
# 資源管理(賬戶管理、SAS 令牌)
dotnet add package Azure.ResourceManager.Maps --prerelease
# 身份驗證必需
dotnet add package Azure.Identity
當前版本:
Azure.Maps.Search: v2.0.0-beta.5Azure.Maps.Routing: v1.0.0-beta.4Azure.Maps.Rendering: v2.0.0-beta.1Azure.Maps.Geolocation: v1.0.0-beta.3Azure.ResourceManager.Maps: v1.1.0-beta.2
環境變數
AZURE_MAPS_SUBSCRIPTION_KEY=<your-subscription-key> # 僅在使用 AzureKeyCredential 身份驗證時需要
AZURE_MAPS_CLIENT_ID=<your-client-id> # 必需:Azure Maps 客戶端 ID
AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境中使用 DefaultAzureCredential 時需要
</your-client-id></your-subscription-key>身份驗證
訂閱金鑰(共享金鑰)
using Azure;
using Azure.Maps.Search;
var subscriptionKey = Environment.GetEnvironmentVariable("AZURE_MAPS_SUBSCRIPTION_KEY");
var credential = new AzureKeyCredential(subscriptionKey);
var client = new MapsSearchClient(credential);
Microsoft Entra 令牌憑據
using Azure.Identity;
using Azure.Maps.Search;
// 本地開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者在生產環境中直接使用特定的憑據:
// 請參閱 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var clientId = Environment.GetEnvironmentVariable("AZURE_MAPS_CLIENT_ID");
var client = new MapsSearchClient(credential, clientId);
</specific_credential>共享訪問簽名 (SAS)
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Maps;
using Azure.ResourceManager.Maps.Models;
using Azure.Maps.Search;
// 使用 Azure 資源管理器進行身份驗證
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
// 獲取地圖賬戶資源
ResourceIdentifier mapsAccountResourceId = MapsAccountResource.CreateResourceIdentifier(
subscriptionId, resourceGroupName, accountName);
MapsAccountResource mapsAccount = armClient.GetMapsAccountResource(mapsAccountResourceId);
// 生成 SAS 令牌
MapsAccountSasContent sasContent = new MapsAccountSasContent(
MapsSigningKey.PrimaryKey,
principalId,
maxRatePerSecond: 500,
start: DateTime.UtcNow.ToString("O"),
expiry: DateTime.UtcNow.AddDays(1).ToString("O"));
Response<mapsaccountsastoken> sas = mapsAccount.GetSas(sasContent);
// 使用 SAS 令牌建立客戶端
var sasCredential = new AzureSasCredential(sas.Value.AccountSasToken);
var client = new MapsSearchClient(sasCredential);
</mapsaccountsastoken>客戶端層次結構
Azure.Maps.Search
└── MapsSearchClient
├── GetGeocoding() → 地理編碼地址
├── GetGeocodingBatch() → 批次地理編碼
├── GetReverseGeocoding() → 座標轉地址
├── GetReverseGeocodingBatch() → 批次反向地理編碼
└── GetPolygon() → 獲取邊界多邊形
Azure.Maps.Routing
└── MapsRoutingClient
├── GetDirections() → 路線指引
├── GetImmediateRouteMatrix() → 路線矩陣(同步,≤100)
├── GetRouteMatrix() → 路線矩陣(非同步,≤700)
└── GetRouteRange() → 等時線/可達範圍
Azure.Maps.Rendering
└── MapsRenderingClient
├── GetMapTile() → 地圖瓦片
├── GetMapStaticImage() → 靜態地圖影象
└── GetCopyrightCaption() → 版權資訊
Azure.Maps.Geolocation
└── MapsGeolocationClient
└── GetCountryCode() → IP 地址轉國家/地區
Azure.Maps.Weather
└── MapsWeatherClient
├── GetCurrentWeatherConditions() → 當前天氣
├── GetDailyForecast() → 每日預報
├── GetHourlyForecast() → 每小時預報
└── GetSevereWeatherAlerts() → 天氣警報
核心工作流
1. 地理編碼(地址轉座標)
using Azure;
using Azure.Maps.Search;
var credential = new AzureKeyCredential(subscriptionKey);
var client = new MapsSearchClient(credential);
Response<geocodingresponse> result = client.GetGeocoding("1 Microsoft Way, Redmond, WA 98052");
foreach (var feature in result.Value.Features)
{
Console.WriteLine($"Coordinates: {string.Join(",", feature.Geometry.Coordinates)}");
Console.WriteLine($"Address: {feature.Properties.Address.FormattedAddress}");
Console.WriteLine($"Confidence: {feature.Properties.Confidence}");
}
</geocodingresponse>2. 批次地理編碼
using Azure.Maps.Search.Models.Queries;
List<geocodingquery> queries = new List<geocodingquery>
{
new GeocodingQuery() { Query = "400 Broad St, Seattle, WA" },
new GeocodingQuery() { Query = "1 Microsoft Way, Redmond, WA" },
new GeocodingQuery() { AddressLine = "Space Needle", Top = 1 },
};
Response<geocodingbatchresponse> results = client.GetGeocodingBatch(queries);
foreach (var batchItem in results.Value.BatchItems)
{
foreach (var feature in batchItem.Features)
{
Console.WriteLine($"Coordinates: {string.Join(",", feature.Geometry.Coordinates)}");
}
}
</geocodingbatchresponse></geocodingquery></geocodingquery>3. 反向地理編碼(座標轉地址)
using Azure.Core.GeoJson;
GeoPosition coordinates = new GeoPosition(-122.138685, 47.6305637);
Response<geocodingresponse> result = client.GetReverseGeocoding(coordinates);
foreach (var feature in result.Value.Features)
{
Console.WriteLine($"Address: {feature.Properties.Address.FormattedAddress}");
Console.WriteLine($"Locality: {feature.Properties.Address.Locality}");
}
</geocodingresponse>4. 獲取邊界多邊形
using Azure.Maps.Search.Models;
GetPolygonOptions options = new GetPolygonOptions()
{
Coordinates = new GeoPosition(-122.204141, 47.61256),
ResultType = BoundaryResultTypeEnum.Locality,
Resolution = ResolutionEnum.Small,
};
Response<boundary> result = client.GetPolygon(options);
Console.WriteLine($"Boundary copyright: {result.Value.Properties?.Copyright}");
Console.WriteLine($"Polygon count: {result.Value.Geometry.Count}");
</boundary>5. 路線指引
using Azure;
using Azure.Core.GeoJson;
using Azure.Maps.Routing;
using Azure.Maps.Routing.Models;
var client = new MapsRoutingClient(new AzureKeyCredential(subscriptionKey));
List<geoposition> routePoints = new List<geoposition>()
{
new GeoPosition(-122.34, 47.61), // 西雅圖
new GeoPosition(-122.13, 47.64) // 雷德蒙德
};
RouteDirectionQuery query = new RouteDirectionQuery(routePoints);
Response<routedirections> result = client.GetDirections(query);
foreach (var route in result.Value.Routes)
{
Console.WriteLine($"Distance: {route.Summary.LengthInMeters} meters");
Console.WriteLine($"Duration: {route.Summary.TravelTimeDuration}");
foreach (RouteLeg leg in route.Legs)
{
Console.WriteLine($"Leg points: {leg.Points.Count}");
}
}
</routedirections></geoposition></geoposition>6. 帶選項的路線指引
RouteDirectionOptions options = new RouteDirectionOptions()
{
RouteType = RouteType.Fastest,
UseTrafficData = true,
TravelMode = TravelMode.Bicycle,
Language = RoutingLanguage.EnglishUsa,
InstructionsType = RouteInstructionsType.Text,
};
RouteDirectionQuery query = new RouteDirectionQuery(routePoints)
{
RouteDirectionOptions = options
};
Response<routedirections> result = client.GetDirections(query);
</routedirections>7. 路線矩陣
RouteMatrixQuery routeMatrixQuery = new RouteMatrixQuery
{
Origins = new List<geoposition>()
{
new GeoPosition(-122.34, 47.61),
new GeoPosition(-122.13, 47.64)
},
Destinations = new List<geoposition>()
{
new GeoPosition(-122.20, 47.62),
new GeoPosition(-122.40, 47.65)
},
};
// 同步(最多 100 條路線組合)
Response<routematrixresult> result = client.GetImmediateRouteMatrix(routeMatrixQuery);
foreach (var cell in result.Value.Matrix.SelectMany(row => row))
{
Console.WriteLine($"Distance: {cell.Response?.RouteSummary?.LengthInMeters}");
Console.WriteLine($"Duration: {cell.Response?.RouteSummary?.TravelTimeDuration}");
}
// 非同步(最多 700 條路線組合)
RouteMatrixOptions routeMatrixOptions = new RouteMatrixOptions(routeMatrixQuery)
{
TravelTimeType = TravelTimeType.All,
};
GetRouteMatrixOperation asyncResult = client.GetRouteMatrix(WaitUntil.Completed, routeMatrixOptions);
</routematrixresult></geoposition></geoposition>8. 路線範圍(等時線)
RouteRangeOptions options = new RouteRangeOptions(-122.34, 47.61)
{
TimeBudget = new TimeSpan(0, 20, 0) // 20 分鐘
};
Response<routerangeresult> result = client.GetRouteRange(options);
// result.Value.ReachableRange 包含多邊形
Console.WriteLine($"Boundary points: {result.Value.ReachableRange.Boundary.Count}");
</routerangeresult>9. 獲取地圖瓦片
using Azure;
using Azure.Maps.Rendering;
var client = new MapsRenderingClient(new AzureKeyCredential(subscriptionKey));
int zoom = 10;
int tileSize = 256;
// 將座標轉換為瓦片索引
MapTileIndex tileIndex = MapsRenderingClient.PositionToTileXY(
new GeoPosition(13.3854, 52.517), zoom, tileSize);
// 獲取地圖瓦片
GetMapTileOptions options = new GetMapTileOptions(
MapTileSetId.MicrosoftImagery,
new MapTileIndex(tileIndex.X, tileIndex.Y, zoom)
);
Response<stream> mapTile = client.GetMapTile(options);
// 儲存到檔案
using (FileStream fileStream = File.Create("./MapTile.png"))
{
mapTile.Value.CopyTo(fileStream);
}
</stream>10. IP 地理定位
using System.Net;
using Azure;
using Azure.Maps.Geolocation;
var client = new MapsGeolocationClient(new AzureKeyCredential(subscriptionKey));
IPAddress ipAddress = IPAddress.Parse("2001:4898:80e8:b::189");
Response<countryregionresult> result = client.GetCountryCode(ipAddress);
Console.WriteLine($"Country ISO Code: {result.Value.IsoCode}");
</countryregionresult>11. 當前天氣
using Azure;
using Azure.Core.GeoJson;
using Azure.Maps.Weather;
var client = new MapsWeatherClient(new AzureKeyCredential(subscriptionKey));
var position = new GeoPosition(-122.13071, 47.64011);
var options = new GetCurrentWeatherConditionsOptions(position);
Response<currentconditionsresult> result = client.GetCurrentWeatherConditions(options);
foreach (var condition in result.Value.Results)
{
Console.WriteLine($"Temperature: {condition.Temperature.Value} {condition.Temperature.Unit}");
Console.WriteLine($"Weather: {condition.Phrase}");
Console.WriteLine($"Humidity: {condition.RelativeHumidity}%");
}
</currentconditionsresult>關鍵型別參考
搜尋包
| 型別 | 用途 |
|---|---|
| `MapsSearchClient` | 搜尋操作的主要客戶端 |
| `GeocodingResponse` | 地理編碼結果 |
| `GeocodingBatchResponse` | 批次地理編碼結果 |
| `GeocodingQuery` | 批次地理編碼查詢 |
| `ReverseGeocodingQuery` | 批次反向地理編碼查詢 |
| `GetPolygonOptions` | 多邊形檢索選項 |
| `Boundary` | 邊界多邊形結果 |
| `BoundaryResultTypeEnum` | 邊界型別(區域、行政區等) |
| `ResolutionEnum` | 多邊形解析度(小、中、大) |
路線規劃包
| 型別 | 用途 |
|---|---|
| `MapsRoutingClient` | 路線操作的主要客戶端 |
| `RouteDirectionQuery` | 路線指引查詢 |
| `RouteDirectionOptions` | 路線計算選項 |
| `RouteDirections` | 路線指引結果 |
| `RouteLeg` | 路線分段 |
| `RouteMatrixQuery` | 路線矩陣查詢 |
| `RouteMatrixResult` | 路線矩陣結果 |
| `RouteRangeOptions` | 等時線選項 |
| `RouteRangeResult` | 等時線結果 |
| `RouteType` | 路線型別(最快、最短、環保、刺激) |
| `TravelMode` | 出行方式(汽車、卡車、腳踏車、步行) |
渲染包
| 型別 | 用途 |
|---|---|
| `MapsRenderingClient` | 渲染的主要客戶端 |
| `GetMapTileOptions` | 地圖瓦片選項 |
| `MapTileIndex` | 瓦片座標(X, Y, 縮放級別) |
| `MapTileSetId` | 瓦片集識別符號 |
通用型別
| 型別 | 用途 |
|---|---|
| `GeoPosition` | 地理座標(經度, 緯度) |
| `GeoBoundingBox` | 地理區域的邊界框 |
最佳實踐
- 生產環境使用 Entra ID — 優先於訂閱金鑰
- 批次操作 — 對多個地址使用批次地理編碼
- 快取結果 — 地理編碼結果不經常更改
- 使用適當的瓦片大小 — 根據顯示需求選擇 256 或 512 畫素
- 處理速率限制 — 實現指數退避演算法
- 使用非同步路線矩陣 — 用於大型矩陣計算(>100)
- 考慮交通資料 — 設定
UseTrafficData = true以獲得準確的預計到達時間
錯誤處理
try
{
Response<geocodingresponse> result = client.GetGeocoding(address);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Status: {ex.Status}");
Console.WriteLine($"Error: {ex.Message}");
switch (ex.Status)
{
case 400:
// 無效的請求引數
break;
case 401:
// 身份驗證失敗
break;
case 429:
// 速率受限 - 實現退避演算法
break;
}
}
</geocodingresponse>相關 SDK
| SDK | 用途 | 安裝 |
|---|---|---|
| `Azure.Maps.Search` | 地理編碼、搜尋 | `dotnet add package Azure.Maps.Search --prerelease` |
| `Azure.Maps.Routing` | 路線指引、矩陣 | `dotnet add package Azure.Maps.Routing --prerelease` |
| `Azure.Maps.Rendering` | 地圖瓦片、影象 | `dotnet add package Azure.Maps.Rendering --prerelease` |
| `Azure.Maps.Geolocation` | IP 地理定位 | `dotnet add package Azure.Maps.Geolocation --prerelease` |
| `Azure.Maps.Weather` | 天氣資料 | `dotnet add package Azure.Maps.Weather --prerelease` |
| `Azure.ResourceManager.Maps` | 賬戶管理 | `dotnet add package Azure.ResourceManager.Maps --prerelease` |
參考連結
| 資源 | URL |
|---|---|
| Azure Maps 文件 | https://learn.microsoft.com/azure/azure-maps/ |
| 搜尋 API 參考 | https://learn.microsoft.com/dotnet/api/azure.maps.search |
| 路線規劃 API 參考 | https://learn.microsoft.com/dotnet/api/azure.maps.routing |
| GitHub 原始碼 | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/maps |
| 定價 | https://azure.microsoft.com/pricing/details/azure-maps/ |
---
name: azure-maps-search-dotnet
description: Integrate Azure Maps location-based services into .NET applications for geocoding, routing, rendering, geolocation, and weather data.
license: MIT
---
# Azure Maps (.NET)
Azure Maps SDK for .NET providing location-based services: geocoding, routing, rendering, geolocation, and weather.
## Installation
```bash
# Search (geocoding, reverse geocoding)
dotnet add package Azure.Maps.Search --prerelease
# Routing (directions, route matrix)
dotnet add package Azure.Maps.Routing --prerelease
# Rendering (map tiles, static images)
dotnet add package Azure.Maps.Rendering --prerelease
# Geolocation (IP to location)
dotnet add package Azure.Maps.Geolocation --prerelease
# Weather
dotnet add package Azure.Maps.Weather --prerelease
# Resource Management (account management, SAS tokens)
dotnet add package Azure.ResourceManager.Maps --prerelease
# Required for authentication
dotnet add package Azure.Identity
```
**Current Versions**:
- `Azure.Maps.Search`: v2.0.0-beta.5
- `Azure.Maps.Routing`: v1.0.0-beta.4
- `Azure.Maps.Rendering`: v2.0.0-beta.1
- `Azure.Maps.Geolocation`: v1.0.0-beta.3
- `Azure.ResourceManager.Maps`: v1.1.0-beta.2
## Environment Variables
```bash
AZURE_MAPS_SUBSCRIPTION_KEY=<your-subscription-key> # Only required for AzureKeyCredential auth
AZURE_MAPS_CLIENT_ID=<your-client-id> # Required: Azure Maps client ID
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication
### Subscription Key (Shared Key)
```csharp
using Azure;
using Azure.Maps.Search;
var subscriptionKey = Environment.GetEnvironmentVariable("AZURE_MAPS_SUBSCRIPTION_KEY");
var credential = new AzureKeyCredential(subscriptionKey);
var client = new MapsSearchClient(credential);
```
### Microsoft Entra Token Credential
```csharp
using Azure.Identity;
using Azure.Maps.Search;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var clientId = Environment.GetEnvironmentVariable("AZURE_MAPS_CLIENT_ID");
var client = new MapsSearchClient(credential, clientId);
```
### Shared Access Signature (SAS)
```csharp
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Maps;
using Azure.ResourceManager.Maps.Models;
using Azure.Maps.Search;
// Authenticate with Azure Resource Manager
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
// Get Maps account resource
ResourceIdentifier mapsAccountResourceId = MapsAccountResource.CreateResourceIdentifier(
subscriptionId, resourceGroupName, accountName);
MapsAccountResource mapsAccount = armClient.GetMapsAccountResource(mapsAccountResourceId);
// Generate SAS token
MapsAccountSasContent sasContent = new MapsAccountSasContent(
MapsSigningKey.PrimaryKey,
principalId,
maxRatePerSecond: 500,
start: DateTime.UtcNow.ToString("O"),
expiry: DateTime.UtcNow.AddDays(1).ToString("O"));
Response<MapsAccountSasToken> sas = mapsAccount.GetSas(sasContent);
// Create client with SAS token
var sasCredential = new AzureSasCredential(sas.Value.AccountSasToken);
var client = new MapsSearchClient(sasCredential);
```
## Client Hierarchy
```
Azure.Maps.Search
└── MapsSearchClient
├── GetGeocoding() → Geocode addresses
├── GetGeocodingBatch() → Batch geocoding
├── GetReverseGeocoding() → Coordinates to address
├── GetReverseGeocodingBatch() → Batch reverse geocoding
└── GetPolygon() → Get boundary polygons
Azure.Maps.Routing
└── MapsRoutingClient
├── GetDirections() → Route directions
├── GetImmediateRouteMatrix() → Route matrix (sync, ≤100)
├── GetRouteMatrix() → Route matrix (async, ≤700)
└── GetRouteRange() → Isochrone/reachable range
Azure.Maps.Rendering
└── MapsRenderingClient
├── GetMapTile() → Map tiles
├── GetMapStaticImage() → Static map images
└── GetCopyrightCaption() → Copyright info
Azure.Maps.Geolocation
└── MapsGeolocationClient
└── GetCountryCode() → IP to country/region
Azure.Maps.Weather
└── MapsWeatherClient
├── GetCurrentWeatherConditions() → Current weather
├── GetDailyForecast() → Daily forecast
├── GetHourlyForecast() → Hourly forecast
└── GetSevereWeatherAlerts() → Weather alerts
```
## Core Workflows
### 1. Geocoding (Address to Coordinates)
```csharp
using Azure;
using Azure.Maps.Search;
var credential = new AzureKeyCredential(subscriptionKey);
var client = new MapsSearchClient(credential);
Response<GeocodingResponse> result = client.GetGeocoding("1 Microsoft Way, Redmond, WA 98052");
foreach (var feature in result.Value.Features)
{
Console.WriteLine($"Coordinates: {string.Join(",", feature.Geometry.Coordinates)}");
Console.WriteLine($"Address: {feature.Properties.Address.FormattedAddress}");
Console.WriteLine($"Confidence: {feature.Properties.Confidence}");
}
```
### 2. Batch Geocoding
```csharp
using Azure.Maps.Search.Models.Queries;
List<GeocodingQuery> queries = new List<GeocodingQuery>
{
new GeocodingQuery() { Query = "400 Broad St, Seattle, WA" },
new GeocodingQuery() { Query = "1 Microsoft Way, Redmond, WA" },
new GeocodingQuery() { AddressLine = "Space Needle", Top = 1 },
};
Response<GeocodingBatchResponse> results = client.GetGeocodingBatch(queries);
foreach (var batchItem in results.Value.BatchItems)
{
foreach (var feature in batchItem.Features)
{
Console.WriteLine($"Coordinates: {string.Join(",", feature.Geometry.Coordinates)}");
}
}
```
### 3. Reverse Geocoding (Coordinates to Address)
```csharp
using Azure.Core.GeoJson;
GeoPosition coordinates = new GeoPosition(-122.138685, 47.6305637);
Response<GeocodingResponse> result = client.GetReverseGeocoding(coordinates);
foreach (var feature in result.Value.Features)
{
Console.WriteLine($"Address: {feature.Properties.Address.FormattedAddress}");
Console.WriteLine($"Locality: {feature.Properties.Address.Locality}");
}
```
### 4. Get Boundary Polygon
```csharp
using Azure.Maps.Search.Models;
GetPolygonOptions options = new GetPolygonOptions()
{
Coordinates = new GeoPosition(-122.204141, 47.61256),
ResultType = BoundaryResultTypeEnum.Locality,
Resolution = ResolutionEnum.Small,
};
Response<Boundary> result = client.GetPolygon(options);
Console.WriteLine($"Boundary copyright: {result.Value.Properties?.Copyright}");
Console.WriteLine($"Polygon count: {result.Value.Geometry.Count}");
```
### 5. Route Directions
```csharp
using Azure;
using Azure.Core.GeoJson;
using Azure.Maps.Routing;
using Azure.Maps.Routing.Models;
var client = new MapsRoutingClient(new AzureKeyCredential(subscriptionKey));
List<GeoPosition> routePoints = new List<GeoPosition>()
{
new GeoPosition(-122.34, 47.61), // Seattle
new GeoPosition(-122.13, 47.64) // Redmond
};
RouteDirectionQuery query = new RouteDirectionQuery(routePoints);
Response<RouteDirections> result = client.GetDirections(query);
foreach (var route in result.Value.Routes)
{
Console.WriteLine($"Distance: {route.Summary.LengthInMeters} meters");
Console.WriteLine($"Duration: {route.Summary.TravelTimeDuration}");
foreach (RouteLeg leg in route.Legs)
{
Console.WriteLine($"Leg points: {leg.Points.Count}");
}
}
```
### 6. Route Directions with Options
```csharp
RouteDirectionOptions options = new RouteDirectionOptions()
{
RouteType = RouteType.Fastest,
UseTrafficData = true,
TravelMode = TravelMode.Bicycle,
Language = RoutingLanguage.EnglishUsa,
InstructionsType = RouteInstructionsType.Text,
};
RouteDirectionQuery query = new RouteDirectionQuery(routePoints)
{
RouteDirectionOptions = options
};
Response<RouteDirections> result = client.GetDirections(query);
```
### 7. Route Matrix
```csharp
RouteMatrixQuery routeMatrixQuery = new RouteMatrixQuery
{
Origins = new List<GeoPosition>()
{
new GeoPosition(-122.34, 47.61),
new GeoPosition(-122.13, 47.64)
},
Destinations = new List<GeoPosition>()
{
new GeoPosition(-122.20, 47.62),
new GeoPosition(-122.40, 47.65)
},
};
// Synchronous (up to 100 route combinations)
Response<RouteMatrixResult> result = client.GetImmediateRouteMatrix(routeMatrixQuery);
foreach (var cell in result.Value.Matrix.SelectMany(row => row))
{
Console.WriteLine($"Distance: {cell.Response?.RouteSummary?.LengthInMeters}");
Console.WriteLine($"Duration: {cell.Response?.RouteSummary?.TravelTimeDuration}");
}
// Asynchronous (up to 700 route combinations)
RouteMatrixOptions routeMatrixOptions = new RouteMatrixOptions(routeMatrixQuery)
{
TravelTimeType = TravelTimeType.All,
};
GetRouteMatrixOperation asyncResult = client.GetRouteMatrix(WaitUntil.Completed, routeMatrixOptions);
```
### 8. Route Range (Isochrone)
```csharp
RouteRangeOptions options = new RouteRangeOptions(-122.34, 47.61)
{
TimeBudget = new TimeSpan(0, 20, 0) // 20 minutes
};
Response<RouteRangeResult> result = client.GetRouteRange(options);
// result.Value.ReachableRange contains the polygon
Console.WriteLine($"Boundary points: {result.Value.ReachableRange.Boundary.Count}");
```
### 9. Get Map Tiles
```csharp
using Azure;
using Azure.Maps.Rendering;
var client = new MapsRenderingClient(new AzureKeyCredential(subscriptionKey));
int zoom = 10;
int tileSize = 256;
// Convert coordinates to tile index
MapTileIndex tileIndex = MapsRenderingClient.PositionToTileXY(
new GeoPosition(13.3854, 52.517), zoom, tileSize);
// Fetch map tile
GetMapTileOptions options = new GetMapTileOptions(
MapTileSetId.MicrosoftImagery,
new MapTileIndex(tileIndex.X, tileIndex.Y, zoom)
);
Response<Stream> mapTile = client.GetMapTile(options);
// Save to file
using (FileStream fileStream = File.Create("./MapTile.png"))
{
mapTile.Value.CopyTo(fileStream);
}
```
### 10. IP Geolocation
```csharp
using System.Net;
using Azure;
using Azure.Maps.Geolocation;
var client = new MapsGeolocationClient(new AzureKeyCredential(subscriptionKey));
IPAddress ipAddress = IPAddress.Parse("2001:4898:80e8:b::189");
Response<CountryRegionResult> result = client.GetCountryCode(ipAddress);
Console.WriteLine($"Country ISO Code: {result.Value.IsoCode}");
```
### 11. Current Weather
```csharp
using Azure;
using Azure.Core.GeoJson;
using Azure.Maps.Weather;
var client = new MapsWeatherClient(new AzureKeyCredential(subscriptionKey));
var position = new GeoPosition(-122.13071, 47.64011);
var options = new GetCurrentWeatherConditionsOptions(position);
Response<CurrentConditionsResult> result = client.GetCurrentWeatherConditions(options);
foreach (var condition in result.Value.Results)
{
Console.WriteLine($"Temperature: {condition.Temperature.Value} {condition.Temperature.Unit}");
Console.WriteLine($"Weather: {condition.Phrase}");
Console.WriteLine($"Humidity: {condition.RelativeHumidity}%");
}
```
## Key Types Reference
### Search Package
| Type | Purpose |
|------|---------|
| `MapsSearchClient` | Main client for search operations |
| `GeocodingResponse` | Geocoding result |
| `GeocodingBatchResponse` | Batch geocoding result |
| `GeocodingQuery` | Query for batch geocoding |
| `ReverseGeocodingQuery` | Query for batch reverse geocoding |
| `GetPolygonOptions` | Options for polygon retrieval |
| `Boundary` | Boundary polygon result |
| `BoundaryResultTypeEnum` | Boundary type (Locality, AdminDistrict, etc.) |
| `ResolutionEnum` | Polygon resolution (Small, Medium, Large) |
### Routing Package
| Type | Purpose |
|------|---------|
| `MapsRoutingClient` | Main client for routing operations |
| `RouteDirectionQuery` | Query for route directions |
| `RouteDirectionOptions` | Route calculation options |
| `RouteDirections` | Route directions result |
| `RouteLeg` | Segment of a route |
| `RouteMatrixQuery` | Query for route matrix |
| `RouteMatrixResult` | Route matrix result |
| `RouteRangeOptions` | Options for isochrone |
| `RouteRangeResult` | Isochrone result |
| `RouteType` | Route type (Fastest, Shortest, Eco, Thrilling) |
| `TravelMode` | Travel mode (Car, Truck, Bicycle, Pedestrian) |
### Rendering Package
| Type | Purpose |
|------|---------|
| `MapsRenderingClient` | Main client for rendering |
| `GetMapTileOptions` | Map tile options |
| `MapTileIndex` | Tile coordinates (X, Y, Zoom) |
| `MapTileSetId` | Tile set identifier |
### Common Types
| Type | Purpose |
|------|---------|
| `GeoPosition` | Geographic position (longitude, latitude) |
| `GeoBoundingBox` | Bounding box for geographic area |
## Best Practices
1. **Use Entra ID for production** — Prefer over subscription keys
2. **Batch operations** — Use batch geocoding for multiple addresses
3. **Cache results** — Geocoding results don't change frequently
4. **Use appropriate tile sizes** — 256 or 512 pixels based on display
5. **Handle rate limits** — Implement exponential backoff
6. **Use async route matrix** — For large matrix calculations (>100)
7. **Consider traffic data** — Set `UseTrafficData = true` for accurate ETAs
## Error Handling
```csharp
try
{
Response<GeocodingResponse> result = client.GetGeocoding(address);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Status: {ex.Status}");
Console.WriteLine($"Error: {ex.Message}");
switch (ex.Status)
{
case 400:
// Invalid request parameters
break;
case 401:
// Authentication failed
break;
case 429:
// Rate limited - implement backoff
break;
}
}
```
## Related SDKs
| SDK | Purpose | Install |
|-----|---------|---------|
| `Azure.Maps.Search` | Geocoding, search | `dotnet add package Azure.Maps.Search --prerelease` |
| `Azure.Maps.Routing` | Directions, matrix | `dotnet add package Azure.Maps.Routing --prerelease` |
| `Azure.Maps.Rendering` | Map tiles, images | `dotnet add package Azure.Maps.Rendering --prerelease` |
| `Azure.Maps.Geolocation` | IP geolocation | `dotnet add package Azure.Maps.Geolocation --prerelease` |
| `Azure.Maps.Weather` | Weather data | `dotnet add package Azure.Maps.Weather --prerelease` |
| `Azure.ResourceManager.Maps` | Account management | `dotnet add package Azure.ResourceManager.Maps --prerelease` |
## Reference Links
| Resource | URL |
|----------|-----|
| Azure Maps Documentation | https://learn.microsoft.com/azure/azure-maps/ |
| Search API Reference | https://learn.microsoft.com/dotnet/api/azure.maps.search |
| Routing API Reference | https://learn.microsoft.com/dotnet/api/azure.maps.routing |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/maps |
| Pricing | https://azure.microsoft.com/pricing/details/azure-maps/ |
所有檔案
0 個檔案安裝 azure-maps-search-dotnet
將技能檔案下載並解壓至你的 .claude/skills/ 目錄。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-maps-search-dotnet # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
