|
Add this skill
npx mdskills install sickn33/azure-maps-search-dotnetComprehensive Azure Maps SDK documentation with excellent code examples and authentication patterns
1---2name: azure-maps-search-dotnet3description: |4 Azure Maps SDK for .NET. Location-based services including geocoding, routing, rendering, geolocation, and weather. Use for address search, directions, map tiles, IP geolocation, and weather data. Triggers: "Azure Maps", "MapsSearchClient", "MapsRoutingClient", "MapsRenderingClient", "geocoding .NET", "route directions", "map tiles", "geolocation".5package: Azure.Maps.Search6---78# Azure Maps (.NET)910Azure Maps SDK for .NET providing location-based services: geocoding, routing, rendering, geolocation, and weather.1112## Installation1314```bash15# Search (geocoding, reverse geocoding)16dotnet add package Azure.Maps.Search --prerelease1718# Routing (directions, route matrix)19dotnet add package Azure.Maps.Routing --prerelease2021# Rendering (map tiles, static images)22dotnet add package Azure.Maps.Rendering --prerelease2324# Geolocation (IP to location)25dotnet add package Azure.Maps.Geolocation --prerelease2627# Weather28dotnet add package Azure.Maps.Weather --prerelease2930# Resource Management (account management, SAS tokens)31dotnet add package Azure.ResourceManager.Maps --prerelease3233# Required for authentication34dotnet add package Azure.Identity35```3637**Current Versions**:38- `Azure.Maps.Search`: v2.0.0-beta.539- `Azure.Maps.Routing`: v1.0.0-beta.440- `Azure.Maps.Rendering`: v2.0.0-beta.141- `Azure.Maps.Geolocation`: v1.0.0-beta.342- `Azure.ResourceManager.Maps`: v1.1.0-beta.24344## Environment Variables4546```bash47AZURE_MAPS_SUBSCRIPTION_KEY=<your-subscription-key>48AZURE_MAPS_CLIENT_ID=<your-client-id> # For Entra ID auth49```5051## Authentication5253### Subscription Key (Shared Key)5455```csharp56using Azure;57using Azure.Maps.Search;5859var subscriptionKey = Environment.GetEnvironmentVariable("AZURE_MAPS_SUBSCRIPTION_KEY");60var credential = new AzureKeyCredential(subscriptionKey);6162var client = new MapsSearchClient(credential);63```6465### Microsoft Entra ID (Recommended for Production)6667```csharp68using Azure.Identity;69using Azure.Maps.Search;7071var credential = new DefaultAzureCredential();72var clientId = Environment.GetEnvironmentVariable("AZURE_MAPS_CLIENT_ID");7374var client = new MapsSearchClient(credential, clientId);75```7677### Shared Access Signature (SAS)7879```csharp80using Azure;81using Azure.Core;82using Azure.Identity;83using Azure.ResourceManager;84using Azure.ResourceManager.Maps;85using Azure.ResourceManager.Maps.Models;86using Azure.Maps.Search;8788// Authenticate with Azure Resource Manager89ArmClient armClient = new ArmClient(new DefaultAzureCredential());9091// Get Maps account resource92ResourceIdentifier mapsAccountResourceId = MapsAccountResource.CreateResourceIdentifier(93 subscriptionId, resourceGroupName, accountName);94MapsAccountResource mapsAccount = armClient.GetMapsAccountResource(mapsAccountResourceId);9596// Generate SAS token97MapsAccountSasContent sasContent = new MapsAccountSasContent(98 MapsSigningKey.PrimaryKey,99 principalId,100 maxRatePerSecond: 500,101 start: DateTime.UtcNow.ToString("O"),102 expiry: DateTime.UtcNow.AddDays(1).ToString("O"));103104Response<MapsAccountSasToken> sas = mapsAccount.GetSas(sasContent);105106// Create client with SAS token107var sasCredential = new AzureSasCredential(sas.Value.AccountSasToken);108var client = new MapsSearchClient(sasCredential);109```110111## Client Hierarchy112113```114Azure.Maps.Search115└── MapsSearchClient116 ├── GetGeocoding() → Geocode addresses117 ├── GetGeocodingBatch() → Batch geocoding118 ├── GetReverseGeocoding() → Coordinates to address119 ├── GetReverseGeocodingBatch() → Batch reverse geocoding120 └── GetPolygon() → Get boundary polygons121122Azure.Maps.Routing123└── MapsRoutingClient124 ├── GetDirections() → Route directions125 ├── GetImmediateRouteMatrix() → Route matrix (sync, ≤100)126 ├── GetRouteMatrix() → Route matrix (async, ≤700)127 └── GetRouteRange() → Isochrone/reachable range128129Azure.Maps.Rendering130└── MapsRenderingClient131 ├── GetMapTile() → Map tiles132 ├── GetMapStaticImage() → Static map images133 └── GetCopyrightCaption() → Copyright info134135Azure.Maps.Geolocation136└── MapsGeolocationClient137 └── GetCountryCode() → IP to country/region138139Azure.Maps.Weather140└── MapsWeatherClient141 ├── GetCurrentWeatherConditions() → Current weather142 ├── GetDailyForecast() → Daily forecast143 ├── GetHourlyForecast() → Hourly forecast144 └── GetSevereWeatherAlerts() → Weather alerts145```146147## Core Workflows148149### 1. Geocoding (Address to Coordinates)150151```csharp152using Azure;153using Azure.Maps.Search;154155var credential = new AzureKeyCredential(subscriptionKey);156var client = new MapsSearchClient(credential);157158Response<GeocodingResponse> result = client.GetGeocoding("1 Microsoft Way, Redmond, WA 98052");159160foreach (var feature in result.Value.Features)161{162 Console.WriteLine($"Coordinates: {string.Join(",", feature.Geometry.Coordinates)}");163 Console.WriteLine($"Address: {feature.Properties.Address.FormattedAddress}");164 Console.WriteLine($"Confidence: {feature.Properties.Confidence}");165}166```167168### 2. Batch Geocoding169170```csharp171using Azure.Maps.Search.Models.Queries;172173List<GeocodingQuery> queries = new List<GeocodingQuery>174{175 new GeocodingQuery() { Query = "400 Broad St, Seattle, WA" },176 new GeocodingQuery() { Query = "1 Microsoft Way, Redmond, WA" },177 new GeocodingQuery() { AddressLine = "Space Needle", Top = 1 },178};179180Response<GeocodingBatchResponse> results = client.GetGeocodingBatch(queries);181182foreach (var batchItem in results.Value.BatchItems)183{184 foreach (var feature in batchItem.Features)185 {186 Console.WriteLine($"Coordinates: {string.Join(",", feature.Geometry.Coordinates)}");187 }188}189```190191### 3. Reverse Geocoding (Coordinates to Address)192193```csharp194using Azure.Core.GeoJson;195196GeoPosition coordinates = new GeoPosition(-122.138685, 47.6305637);197Response<GeocodingResponse> result = client.GetReverseGeocoding(coordinates);198199foreach (var feature in result.Value.Features)200{201 Console.WriteLine($"Address: {feature.Properties.Address.FormattedAddress}");202 Console.WriteLine($"Locality: {feature.Properties.Address.Locality}");203}204```205206### 4. Get Boundary Polygon207208```csharp209using Azure.Maps.Search.Models;210211GetPolygonOptions options = new GetPolygonOptions()212{213 Coordinates = new GeoPosition(-122.204141, 47.61256),214 ResultType = BoundaryResultTypeEnum.Locality,215 Resolution = ResolutionEnum.Small,216};217218Response<Boundary> result = client.GetPolygon(options);219220Console.WriteLine($"Boundary copyright: {result.Value.Properties?.Copyright}");221Console.WriteLine($"Polygon count: {result.Value.Geometry.Count}");222```223224### 5. Route Directions225226```csharp227using Azure;228using Azure.Core.GeoJson;229using Azure.Maps.Routing;230using Azure.Maps.Routing.Models;231232var client = new MapsRoutingClient(new AzureKeyCredential(subscriptionKey));233234List<GeoPosition> routePoints = new List<GeoPosition>()235{236 new GeoPosition(-122.34, 47.61), // Seattle237 new GeoPosition(-122.13, 47.64) // Redmond238};239240RouteDirectionQuery query = new RouteDirectionQuery(routePoints);241Response<RouteDirections> result = client.GetDirections(query);242243foreach (var route in result.Value.Routes)244{245 Console.WriteLine($"Distance: {route.Summary.LengthInMeters} meters");246 Console.WriteLine($"Duration: {route.Summary.TravelTimeDuration}");247248 foreach (RouteLeg leg in route.Legs)249 {250 Console.WriteLine($"Leg points: {leg.Points.Count}");251 }252}253```254255### 6. Route Directions with Options256257```csharp258RouteDirectionOptions options = new RouteDirectionOptions()259{260 RouteType = RouteType.Fastest,261 UseTrafficData = true,262 TravelMode = TravelMode.Bicycle,263 Language = RoutingLanguage.EnglishUsa,264 InstructionsType = RouteInstructionsType.Text,265};266267RouteDirectionQuery query = new RouteDirectionQuery(routePoints)268{269 RouteDirectionOptions = options270};271272Response<RouteDirections> result = client.GetDirections(query);273```274275### 7. Route Matrix276277```csharp278RouteMatrixQuery routeMatrixQuery = new RouteMatrixQuery279{280 Origins = new List<GeoPosition>()281 {282 new GeoPosition(-122.34, 47.61),283 new GeoPosition(-122.13, 47.64)284 },285 Destinations = new List<GeoPosition>()286 {287 new GeoPosition(-122.20, 47.62),288 new GeoPosition(-122.40, 47.65)289 },290};291292// Synchronous (up to 100 route combinations)293Response<RouteMatrixResult> result = client.GetImmediateRouteMatrix(routeMatrixQuery);294295foreach (var cell in result.Value.Matrix.SelectMany(row => row))296{297 Console.WriteLine($"Distance: {cell.Response?.RouteSummary?.LengthInMeters}");298 Console.WriteLine($"Duration: {cell.Response?.RouteSummary?.TravelTimeDuration}");299}300301// Asynchronous (up to 700 route combinations)302RouteMatrixOptions routeMatrixOptions = new RouteMatrixOptions(routeMatrixQuery)303{304 TravelTimeType = TravelTimeType.All,305};306GetRouteMatrixOperation asyncResult = client.GetRouteMatrix(WaitUntil.Completed, routeMatrixOptions);307```308309### 8. Route Range (Isochrone)310311```csharp312RouteRangeOptions options = new RouteRangeOptions(-122.34, 47.61)313{314 TimeBudget = new TimeSpan(0, 20, 0) // 20 minutes315};316317Response<RouteRangeResult> result = client.GetRouteRange(options);318319// result.Value.ReachableRange contains the polygon320Console.WriteLine($"Boundary points: {result.Value.ReachableRange.Boundary.Count}");321```322323### 9. Get Map Tiles324325```csharp326using Azure;327using Azure.Maps.Rendering;328329var client = new MapsRenderingClient(new AzureKeyCredential(subscriptionKey));330331int zoom = 10;332int tileSize = 256;333334// Convert coordinates to tile index335MapTileIndex tileIndex = MapsRenderingClient.PositionToTileXY(336 new GeoPosition(13.3854, 52.517), zoom, tileSize);337338// Fetch map tile339GetMapTileOptions options = new GetMapTileOptions(340 MapTileSetId.MicrosoftImagery,341 new MapTileIndex(tileIndex.X, tileIndex.Y, zoom)342);343344Response<Stream> mapTile = client.GetMapTile(options);345346// Save to file347using (FileStream fileStream = File.Create("./MapTile.png"))348{349 mapTile.Value.CopyTo(fileStream);350}351```352353### 10. IP Geolocation354355```csharp356using System.Net;357using Azure;358using Azure.Maps.Geolocation;359360var client = new MapsGeolocationClient(new AzureKeyCredential(subscriptionKey));361362IPAddress ipAddress = IPAddress.Parse("2001:4898:80e8:b::189");363Response<CountryRegionResult> result = client.GetCountryCode(ipAddress);364365Console.WriteLine($"Country ISO Code: {result.Value.IsoCode}");366```367368### 11. Current Weather369370```csharp371using Azure;372using Azure.Core.GeoJson;373using Azure.Maps.Weather;374375var client = new MapsWeatherClient(new AzureKeyCredential(subscriptionKey));376377var position = new GeoPosition(-122.13071, 47.64011);378var options = new GetCurrentWeatherConditionsOptions(position);379380Response<CurrentConditionsResult> result = client.GetCurrentWeatherConditions(options);381382foreach (var condition in result.Value.Results)383{384 Console.WriteLine($"Temperature: {condition.Temperature.Value} {condition.Temperature.Unit}");385 Console.WriteLine($"Weather: {condition.Phrase}");386 Console.WriteLine($"Humidity: {condition.RelativeHumidity}%");387}388```389390## Key Types Reference391392### Search Package393394| Type | Purpose |395|------|---------|396| `MapsSearchClient` | Main client for search operations |397| `GeocodingResponse` | Geocoding result |398| `GeocodingBatchResponse` | Batch geocoding result |399| `GeocodingQuery` | Query for batch geocoding |400| `ReverseGeocodingQuery` | Query for batch reverse geocoding |401| `GetPolygonOptions` | Options for polygon retrieval |402| `Boundary` | Boundary polygon result |403| `BoundaryResultTypeEnum` | Boundary type (Locality, AdminDistrict, etc.) |404| `ResolutionEnum` | Polygon resolution (Small, Medium, Large) |405406### Routing Package407408| Type | Purpose |409|------|---------|410| `MapsRoutingClient` | Main client for routing operations |411| `RouteDirectionQuery` | Query for route directions |412| `RouteDirectionOptions` | Route calculation options |413| `RouteDirections` | Route directions result |414| `RouteLeg` | Segment of a route |415| `RouteMatrixQuery` | Query for route matrix |416| `RouteMatrixResult` | Route matrix result |417| `RouteRangeOptions` | Options for isochrone |418| `RouteRangeResult` | Isochrone result |419| `RouteType` | Route type (Fastest, Shortest, Eco, Thrilling) |420| `TravelMode` | Travel mode (Car, Truck, Bicycle, Pedestrian) |421422### Rendering Package423424| Type | Purpose |425|------|---------|426| `MapsRenderingClient` | Main client for rendering |427| `GetMapTileOptions` | Map tile options |428| `MapTileIndex` | Tile coordinates (X, Y, Zoom) |429| `MapTileSetId` | Tile set identifier |430431### Common Types432433| Type | Purpose |434|------|---------|435| `GeoPosition` | Geographic position (longitude, latitude) |436| `GeoBoundingBox` | Bounding box for geographic area |437438## Best Practices4394401. **Use Entra ID for production** — Prefer over subscription keys4412. **Batch operations** — Use batch geocoding for multiple addresses4423. **Cache results** — Geocoding results don't change frequently4434. **Use appropriate tile sizes** — 256 or 512 pixels based on display4445. **Handle rate limits** — Implement exponential backoff4456. **Use async route matrix** — For large matrix calculations (>100)4467. **Consider traffic data** — Set `UseTrafficData = true` for accurate ETAs447448## Error Handling449450```csharp451try452{453 Response<GeocodingResponse> result = client.GetGeocoding(address);454}455catch (RequestFailedException ex)456{457 Console.WriteLine($"Status: {ex.Status}");458 Console.WriteLine($"Error: {ex.Message}");459460 switch (ex.Status)461 {462 case 400:463 // Invalid request parameters464 break;465 case 401:466 // Authentication failed467 break;468 case 429:469 // Rate limited - implement backoff470 break;471 }472}473```474475## Related SDKs476477| SDK | Purpose | Install |478|-----|---------|---------|479| `Azure.Maps.Search` | Geocoding, search | `dotnet add package Azure.Maps.Search --prerelease` |480| `Azure.Maps.Routing` | Directions, matrix | `dotnet add package Azure.Maps.Routing --prerelease` |481| `Azure.Maps.Rendering` | Map tiles, images | `dotnet add package Azure.Maps.Rendering --prerelease` |482| `Azure.Maps.Geolocation` | IP geolocation | `dotnet add package Azure.Maps.Geolocation --prerelease` |483| `Azure.Maps.Weather` | Weather data | `dotnet add package Azure.Maps.Weather --prerelease` |484| `Azure.ResourceManager.Maps` | Account management | `dotnet add package Azure.ResourceManager.Maps --prerelease` |485486## Reference Links487488| Resource | URL |489|----------|-----|490| Azure Maps Documentation | https://learn.microsoft.com/azure/azure-maps/ |491| Search API Reference | https://learn.microsoft.com/dotnet/api/azure.maps.search |492| Routing API Reference | https://learn.microsoft.com/dotnet/api/azure.maps.routing |493| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/maps |494| Pricing | https://azure.microsoft.com/pricing/details/azure-maps/ |495
Full transparency — inspect the skill content before installing.