opción
HogarHogar Skill Desarrollo de API azure-maps-search-dotnet

azure-maps-search-dotnet

microsoft/skills microsoft/skills

Integra los servicios basados en la ubicación de Azure Maps en aplicaciones .NET para realizar geocodificación, cálculo de rutas, representación, geolocalización y obtener datos meteorológicos.

...Expandir todo
1
Tiempo actualizado 14 de septiembre de 2026

Azure Maps (.NET)

El SDK de Azure Maps para .NET ofrece servicios basados en la ubicación: geocodificación, cálculo de rutas, representación, geolocalización y información meteorológica.

Instalación

# Búsqueda (geocodificación, geocodificación inversa)
dotnet add package Azure.Maps.Search --prerelease

# Cálculo de rutas (indicaciones, matriz de rutas)
dotnet add package Azure.Maps.Routing --prerelease

# Representación (mosaicos de mapa, imágenes estáticas)
dotnet add package Azure.Maps.Rendering --prerelease

# Geolocalización (IP a ubicación)
dotnet add package Azure.Maps.Geolocation --prerelease

# Tiempo
dotnet add package Azure.Maps.Weather --prerelease

# Gestión de recursos (gestión de cuentas, tokens SAS)
dotnet add package Azure.ResourceManager.Maps --prerelease

# Requerido para la autenticación
dotnet add package Azure.Identity

Versiones actuales:

  • 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

Variables de entorno

AZURE_MAPS_SUBSCRIPTION_KEY= # Solo es necesario para la autenticación con AzureKeyCredential
AZURE_MAPS_CLIENT_ID= # Obligatorio: ID de cliente de Azure Maps
AZURE_TOKEN_CREDENTIALS=prod  # Solo es necesario si se utiliza DefaultAzureCredential en producción

Autenticación

Clave de suscripción (clave compartida)

using Azure;
using Azure.Maps.Search;

var subscriptionKey = Environment.GetEnvironmentVariable("AZURE_MAPS_SUBSCRIPTION_KEY");
var credential = new AzureKeyCredential(subscriptionKey);

var client = new MapsSearchClient(credential);

Credencial de token de Microsoft Entra

using Azure.Identity;
using Azure.Maps.Search;

// Desarrollo local: DefaultAzureCredential. Producción: establece AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// O bien, utiliza una credencial específica directamente en producción:
// Consulta 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);

Firma de acceso compartido (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;

// Autenticación con Azure Resource Manager
ArmClient armClient = new ArmClient(new DefaultAzureCredential());

// Obtener el recurso de cuenta de Maps
ResourceIdentifier mapsAccountResourceId = MapsAccountResource.CreateResourceIdentifier(
    subscriptionId, resourceGroupName, accountName);
MapsAccountResource mapsAccount = armClient.GetMapsAccountResource(mapsAccountResourceId);

// Generar un token SAS
MapsAccountSasContent sasContent = new MapsAccountSasContent(
    MapsSigningKey.PrimaryKey, 
    principalId, 
    maxRatePerSecond: 500, 
    start: DateTime.UtcNow.ToString("O"), 
    expiry: DateTime.UtcNow.AddDays(1).ToString("O"));

Respuesta sas = mapsAccount.GetSas(sasContent);

// Crear cliente con el token SAS
var sasCredential = new AzureSasCredential(sas.Value.AccountSasToken);
var client = new MapsSearchClient(sasCredential);

Jerarquía de clientes

Azure.Maps.Search
└── MapsSearchClient
    ├── GetGeocoding()                    → Geocodificación de direcciones
    ├── GetGeocodingBatch()               → Geocodificación por lotes
    ├── GetReverseGeocoding()             → Coordinadas a dirección
    ├── GetReverseGeocodingBatch()        → Geocodificación inversa por lotes
    └── GetPolygon()                      → Obtener polígonos de límites

Azure.Maps.Routing
└── MapsRoutingClient
    ├── GetDirections()                   → Obtener indicaciones de ruta
    ├── GetImmediateRouteMatrix()         → Matriz de rutas (sincrónica, ≤100)
    ├── GetRouteMatrix()                  → Matriz de rutas (asíncrona, ≤700)
    └── GetRouteRange()                   → Isócrona/alcance

Azure.Maps.Rendering
└── MapsRenderingClient
    ├── GetMapTile()                      → Mosaicos de mapa
    ├── GetMapStaticImage()               → Imágenes estáticas de mapa
    └── GetCopyrightCaption()             → Información de derechos de autor

Azure.Maps.Geolocation
└── MapsGeolocationClient
    └── GetCountryCode()                  → De IP a país/región

Azure.Maps.Weather
└── MapsWeatherClient
    ├── GetCurrentWeatherConditions()     → Condiciones meteorológicas actuales
    ├── GetDailyForecast()                → Previsión diaria
    ├── GetHourlyForecast()               → Previsión por horas
    └── GetSevereWeatherAlerts()          → Alertas meteorológicas

Flujos de trabajo principales

1. Geocodificación (de dirección a coordenadas)

using Azure;
using Azure.Maps.Search;

var credential = new AzureKeyCredential(subscriptionKey);
var client = new MapsSearchClient(credential);

Respuesta result = client.GetGeocoding("1 Microsoft Way, Redmond, WA 98052");

foreach (var feature in result.Value.Features)
{
    Console.WriteLine($"Coordenadas: {string.Join(",", feature.Geometry.Coordinates)}");
    Console.WriteLine($"Dirección: {feature.Properties.Address.FormattedAddress}");
    Console.WriteLine($"Nivel de confianza: {feature.Properties.Confidence}");
}

2. Geocodificación por lotes

using Azure.Maps.Search.Models.Queries;

List queries = new List
{
    new GeocodingQuery() { Query = "400 Broad St, Seattle, WA" },
    new GeocodingQuery() { Query = "1 Microsoft Way, Redmond, WA" },
    new GeocodingQuery() { AddressLine = "Space Needle", Top = 1 },
};

Respuesta results = client.GetGeocodingBatch(queries);

foreach (var batchItem in results.Value.BatchItems)
{
    foreach (var feature in batchItem.Features)
    {
        Console.WriteLine($"Coordenadas: {string.Join(",", feature.Geometry.Coordinates)}");
    }
}

3. Geocodificación inversa (de coordenadas a dirección)

using Azure.Core.GeoJson;

GeoPosition coordenadas = new GeoPosition(-122.138685, 47.6305637);
Response resultado = client.GetReverseGeocoding(coordenadas);

foreach (var feature in result.Value.Features)
{
    Console.WriteLine($"Dirección: {feature.Properties.Address.FormattedAddress}");
    Console.WriteLine($"Localidad: {feature.Properties.Address.Locality}");
}

4. Obtener el polígono delimitador

using Azure.Maps.Search.Models;

GetPolygonOptions opciones = new GetPolygonOptions()
{
    Coordinates = new GeoPosition(-122.204141, 47.61256),
    ResultType = BoundaryResultTypeEnum.Locality,
    Resolution = ResolutionEnum.Small,
};

Respuesta result = client.GetPolygon(options);

Console.WriteLine($"Derechos de autor del límite: {result.Value.Properties?.Copyright}");
Console.WriteLine($"Número de polígonos: {result.Value.Geometry.Count}");

5. Indicaciones de ruta

using Azure;
using Azure.Core.GeoJson;
using Azure.Maps.Routing;
using Azure.Maps.Routing.Models;

var client = new MapsRoutingClient(new AzureKeyCredential(subscriptionKey));

List routePoints = new List()
{
    new GeoPosition(-122,34, 47,61),  // Seattle
    new GeoPosition(-122,13, 47,64)   // Redmond
};

RouteDirectionQuery query = new RouteDirectionQuery(routePoints);
Response result = client.GetDirections(query);

foreach (var ruta in result.Value.Routes)
{
    Console.WriteLine($"Distancia: {ruta.Summary.LengthInMeters} metros");
    Console.WriteLine($"Duración: {ruta.Summary.TravelTimeDuration}");
    
    foreach (RouteLeg tramo en ruta.Tramos)
    {
        Console.WriteLine($"Puntos del tramo: {tramo.Puntos.Count}");
    }
}

6. Indicaciones de ruta con opciones

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 result = client.GetDirections(query);

7. Matriz de rutas

RouteMatrixQuery routeMatrixQuery = new RouteMatrixQuery
{
    Origins = new List()
    {
        new GeoPosition(-122.34, 47.61),
        new GeoPosition(-122.13, 47.64)
    },
    Destinos = nueva Lista() 
    { 
        nueva GeoPosition(-122,20; 47,62),
        nueva GeoPosition(-122,40; 47,65)
    },
};

// Sincrónico (hasta 100 combinaciones de rutas)
Respuesta result = client.GetImmediateRouteMatrix(routeMatrixQuery);

foreach (var cell in result.Value.Matrix.SelectMany(row => row))
{
    Console.WriteLine($"Distancia: {cell.Response?.RouteSummary?.LengthInMeters}");
    Console.WriteLine($"Duración: {cell.Response?.RouteSummary?.TravelTimeDuration}");
}

// Asíncrono (hasta 700 combinaciones de rutas)
RouteMatrixOptions routeMatrixOptions = new RouteMatrixOptions(routeMatrixQuery)
{
    TravelTimeType = TravelTimeType.All,
};
GetRouteMatrixOperation asyncResult = client.GetRouteMatrix(WaitUntil.Completed, routeMatrixOptions);

8. Rango de rutas (isócrona)

RouteRangeOptions options = new RouteRangeOptions(-122,34, 47,61)
{
    TimeBudget = new TimeSpan(0, 20, 0)  // 20 minutos
};

Respuesta result = client.GetRouteRange(options);

// result.Value.ReachableRange contiene el polígono
Console.WriteLine($"Puntos límite: {result.Value.ReachableRange.Boundary.Count}");

9. Obtener mosaicos del mapa

using Azure;
using Azure.Maps.Rendering;

var client = new MapsRenderingClient(new AzureKeyCredential(subscriptionKey));

int zoom = 10;
int tileSize = 256;

// Convertir coordenadas a índice de mosaico
MapTileIndex tileIndex = MapsRenderingClient.PositionToTileXY(
    new GeoPosition(13.3854, 52.517), zoom, tileSize);

// Obtener el mosaico del mapa
GetMapTileOptions options = new GetMapTileOptions(
    MapTileSetId.MicrosoftImagery,
    new MapTileIndex(tileIndex.X, tileIndex.Y, zoom)
);

Respuesta mapTile = client.GetMapTile(options);

// Guardar en un archivo
using (FileStream fileStream = File.Create("./MapTile.png"))
{
    mapTile.Value.CopyTo(fileStream);
}

10. Geolocalización por 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 result = client.GetCountryCode(ipAddress);

Console.WriteLine($"Código ISO del país: {result.Value.IsoCode}");

11. Tiempo actual

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);

Respuesta result = client.GetCurrentWeatherConditions(options);

foreach (var condition in result.Value.Results)
{
    Console.WriteLine($"Temperatura: {condition.Temperature.Value} {condition.Temperature.Unit}");
    Console.WriteLine($"Tiempo: {condition.Phrase}");
    Console.WriteLine($"Humedad: {condition.RelativeHumidity} %");
}

Referencia de tipos clave

Paquete de búsqueda

Tipo Finalidad
MapsSearchClient Cliente principal para operaciones de búsqueda
GeocodingResponse Resultado de la geocodificación
Respuesta de geocodificación por lotes Resultado de la geocodificación por lotes
GeocodingQuery Consulta de geocodificación por lotes
ReverseGeocodingQuery Consulta de geocodificación inversa por lotes
GetPolygonOptions Opciones para la obtención de polígonos
Límite Resultado del polígono de límite
BoundaryResultTypeEnum Tipo de límite (localidad, distrito administrativo, etc.)
ResolutionEnum Resolución del polígono (pequeño, mediano, grande)

Paquete de rutas

Tipo Finalidad
MapsRoutingClient Cliente principal para operaciones de cálculo de rutas
RouteDirectionQuery Consulta de indicaciones de ruta
RouteDirectionOptions Opciones de cálculo de rutas
RouteDirections Resultado de las indicaciones de ruta
RouteLeg Segmento de una ruta
RouteMatrixQuery Consulta de la matriz de rutas
Resultado de la matriz de rutas Resultado de la matriz de rutas
RouteRangeOptions Opciones para la isócrona
Resultado del rango de rutas Resultado de la isócrona
Tipo de ruta Tipo de ruta (Más rápida, Más corta, Ecológica, Emocionante)
Modo de desplazamiento Modo de desplazamiento (Coche, Camión, Bicicleta, Peatón)

Paquete de renderizado

Tipo Finalidad
MapsRenderingClient Cliente principal para la representación
GetMapTileOptions Opciones de mosaicos del mapa
MapTileIndex Coordenadas del mosaico (X, Y, zoom)
MapTileSetId Identificador del conjunto de mosaicos

Tipos comunes

Tipo Finalidad
GeoPosition Posición geográfica (longitud, latitud)
GeoBoundingBox Caja delimitadora del área geográfica

Prácticas recomendadas

  1. Utiliza Entra ID para entornos de producción: es preferible a las claves de suscripción
  2. Operaciones por lotes: utiliza la geocodificación por lotes para varias direcciones
  3. Almacenalos resultados en caché: los resultados de la geocodificación no cambian con frecuencia
  4. Utiliza tamaños de mosaico adecuados: 256 o 512 píxeles, según la pantalla
  5. Gestiona los límites de frecuencia: implementa el retroceso exponencial
  6. Utiliza la matriz de rutas asíncrona — Para cálculos de matrices grandes (>100)
  7. Tener en cuenta los datos de tráfico: establecer UseTrafficData = true para obtener horas estimadas de llegada precisas

Gestión de errores

try
{
    Response result = client.GetGeocoding(address);
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Estado: {ex.Status}");
    Console.WriteLine($"Error: {ex.Message}");
    
    switch (ex.Status)
    {
        case 400:
            // Parámetros de solicitud no válidos
            break;
        case 401:
            // Fallo en la autenticación
            break;
        case 429:
            // Límite de frecuencia: aplicar retrasos
            break;
    }
}

SDK relacionados

SDK Finalidad Instalación
Azure.Maps.Search Geocodificación, búsqueda dotnet add package Azure.Maps.Search --prerelease
Azure.Maps.Routing Rutas, matriz dotnet add package Azure.Maps.Routing --prerelease
Azure.Maps.Rendering Mosaicos de mapas, imágenes dotnet add package Azure.Maps.Rendering --prerelease
Azure.Maps.Geolocation Geolocalización por IP dotnet add package Azure.Maps.Geolocation --prerelease
Azure.Maps.Weather Datos meteorológicos dotnet add package Azure.Maps.Weather --prerelease
Azure.ResourceManager.Maps Gestión de cuentas dotnet add package Azure.ResourceManager.Maps --prerelease

Enlaces de referencia

Recurso URL
Documentación de Azure Maps https://learn.microsoft.com/azure/azure-maps/
Referencia de la API de búsqueda https://learn.microsoft.com/dotnet/api/azure.maps.search
Referencia de la API de rutas https://learn.microsoft.com/dotnet/api/azure.maps.routing
Código fuente en GitHub https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/maps
Precios https://azure.microsoft.com/pricing/details/azure-maps/
Ver en GitHub
---
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/ |

Todos los archivos

0 archivos

Instalar azure-maps-search-dotnet

Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

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

Copiar Copiar
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

brightdata-cli
Tiempo actualizado 29 de junio de 2026
humanize
Tiempo actualizado 7 de julio de 2026
agentwallet
Tiempo actualizado 7 de julio de 2026
korean-stock-search
Tiempo actualizado 8 de julio de 2026
OR