Azure Maps .NET 用検索クライアント ライブラリ - バージョン 1.0.0-beta.4

Azure Maps検索は、場所、関心点を照会したり、幾何学的領域内で検索したりできるライブラリです。

ソースコード | API リファレンス ドキュメント | REST API リファレンス ドキュメント | 製品ドキュメント

作業の開始

パッケージをインストールする

NuGet を使用して .NET 用のクライアント ライブラリをインストールします。

dotnet add package Azure.Maps.Search --prerelease

必須コンポーネント

Azure サブスクリプションAzure Maps アカウントが必要です。

新しいAzure Maps アカウントを作成するには、Azure Portal、Azure PowerShell、または Azure CLI を使用できます。 Azure CLI を使う例を次に示します。

az maps account create --kind "Gen2" --account-name "myMapAccountName" --resource-group "<resource group>" --sku "G2"

クライアントを認証する

クライアントを認証するには、共有キー認証と Azure AD の 2 つの方法があります。

共有キー認証

  • [Azure Maps アカウント>の認証] タブに移動します
  • [共有キー認証] セクションのコピーPrimary KeyまたはSecondary Key
// Create a SearchClient that will authenticate through Subscription Key (Shared key)
AzureKeyCredential credential = new AzureKeyCredential("<My Subscription Key>");
MapsSearchClient client = new MapsSearchClient(credential);

Azure AD Authentication

Azure Maps サービスを操作するには、MapsSearchClient クラスのインスタンスを作成する必要があります。 Azure Identity ライブラリを使用すると、対応する Azure サービスを使用して Azure SDK クライアントを認証するための Azure Active Directory サポートを簡単に追加できます。

AAD 認証を使用するには、 、CLIENT_ID、および CLIENT_SECRET を環境変数に設定TENANT_IDし、 メソッドを呼び出DefaultAzureCredential()して資格情報を取得します。 CLIENT_IDCLIENT_SECRET は、Azure Mapsアカウントにアクセスできるサービス プリンシパル ID とシークレットです。

また、[Azure Active Directory 認証] セクションAzure Maps [認証] タブの [クライアント ID] Azure Maps > ページ>から取得できるクライアント ID も必要です。

// Create a MapsSearchClient that will authenticate through AAD
DefaultAzureCredential credential = new DefaultAzureCredential();
string clientId = "<My Map Account Client Id>";
MapsSearchClient client = new MapsSearchClient(credential, clientId);

Shared Access Signature (SAS) 認証

Shared Access Signature (SAS) トークンは、JSON Web トークン (JWT) 形式を使用して作成された認証トークンであり、Azure Maps REST API に対するアプリケーションの認証を証明するために暗号化され署名されます。

SAS トークン認証を統合する前に、 と Azure.ResourceManager.Maps (バージョン1.1.0-beta.2以上) をインストールAzure.ResourceManagerする必要があります。

dotnet add package Azure.ResourceManager
dotnet add package Azure.ResourceManager.Maps --prerelease

このコードでは、Azure Maps SDK と ResourceManager の両方に対して次の行をインポートする必要があります。

using Azure.Core.GeoJson;
using Azure.Maps.Search;
using Azure.Maps.Search.Models;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Maps;
using Azure.ResourceManager.Maps.Models;

その後、 List Sas API を使用して SAS トークンを取得し、 に MapsSearchClient割り当てることができます。 次のコード サンプルでは、特定のマップ アカウント リソースをフェッチし、コードの実行時に 1 日間の有効期限の SAS トークンを作成します。

// Get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
TokenCredential cred = new DefaultAzureCredential();
// Authenticate your client
ArmClient armClient = new ArmClient(cred);

string subscriptionId = "MyMapsSubscriptionId";
string resourceGroupName = "MyMapsResourceGroupName";
string accountName = "MyMapsAccountName";

// Get maps account resource
ResourceIdentifier mapsAccountResourceId = MapsAccountResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, accountName);
MapsAccountResource mapsAccount = armClient.GetMapsAccountResource(mapsAccountResourceId);

// Assign SAS token information
// Every time you want to SAS token, update the principal ID, max rate, start and expiry time
string principalId = "MyManagedIdentityObjectId";
int maxRatePerSecond = 500;

// Set start and expiry time for the SAS token in round-trip date/time format
DateTime now = DateTime.Now;
string start = now.ToString("O");
string expiry = now.AddDays(1).ToString("O");

MapsAccountSasContent sasContent = new MapsAccountSasContent(MapsSigningKey.PrimaryKey, principalId, maxRatePerSecond, start, expiry);
Response<MapsAccountSasToken> sas = mapsAccount.GetSas(sasContent);

// Create a SearchClient that will authenticate via SAS token
AzureSasCredential sasCredential = new AzureSasCredential(sas.Value.AccountSasToken);
MapsSearchClient client = new MapsSearchClient(sasCredential);

主要な概念

MapsSearchClient は次の目的のために設計されています。

  • Azure Mapsエンドポイントと通信して、アドレスまたは場所のポイントに対してクエリを実行する
  • Azure Maps エンドポイントと通信して、一連のエンティティの市区町村や国のアウトラインなどのジオメトリ データを要求する
  • Azure Mapsエンドポイントと通信して、1 つのジオメトリまたはその多く内で自由なフォーム検索を実行する

詳細については、サンプルを参照してください

スレッド セーフ

すべてのクライアント インスタンス メソッドがスレッド セーフであり、相互に独立していることを保証します (ガイドライン)。 これにより、クライアント インスタンスの再利用に関する推奨事項は、スレッド間でも常に安全になります。

その他の概念

クライアント オプション | 応答 | へのアクセス実行時間の長い操作 | エラーの | 処理診断 | あざける | クライアントの有効期間

使用例

サンプルを使用して、さまざまな API について理解することができます。

多角形の取得の例

// Get Addresses
Response<SearchAddressResult> searchResult = await client.SearchAddressAsync("Seattle");

// Extract geometry ids from addresses
string geometry0Id = searchResult.Value.Results[0].DataSources.Geometry.Id;
string geometry1Id = searchResult.Value.Results[1].DataSources.Geometry.Id;

// Extract position coordinates
GeoPosition positionCoordinates = searchResult.Value.Results[0].Position;

// Get polygons from geometry ids
PolygonResult polygonResponse = await client.GetPolygonsAsync(new[] { geometry0Id, geometry1Id });

// Get polygons objects
IReadOnlyList<PolygonObject> polygonList = polygonResponse.Polygons;
Response<SearchAddressResult> fuzzySearchResponse = await client.FuzzySearchAsync("coffee", new FuzzySearchOptions
{
    Coordinates = new GeoPosition(121.56, 25.04),
    Language = SearchLanguage.EnglishUsa
});

// Print out the possible results
Console.WriteLine("The possible results for coffee shop:");
foreach (SearchAddressResultItem result in fuzzySearchResponse.Value.Results)
{
    Console.WriteLine("Coordinate: {0}, Address: {1}",
        result.Position, result.Address.FreeformAddress);
}

リバース検索のクロス ストリート アドレスの例

var reverseResult = await client.ReverseSearchCrossStreetAddressAsync(new ReverseSearchCrossStreetOptions
{
    Coordinates = new GeoPosition(121.0, 24.0),
    Language = SearchLanguage.EnglishUsa
});

検索の構造化アドレスの例

var address = new StructuredAddress
{
    CountryCode = "US",
    StreetNumber = "15127",
    StreetName = "NE 24th Street",
    Municipality = "Redmond",
    CountrySubdivision = "WA",
    PostalCode = "98052"
};
Response<SearchAddressResult> searchResult = await client.SearchStructuredAddressAsync(address);

SearchAddressResultItem resultItem = searchResult.Value.Results[0];
Console.WriteLine("First result - Coordinate: {0}, Address: {1}",
    resultItem.Position, resultItem.Address.FreeformAddress);

ジオメトリ内の検索の例

GeoPolygon sfPolygon = new GeoPolygon(new[]
{
    new GeoPosition(-122.43576049804686, 37.752415234354402),
    new GeoPosition(-122.4330139160, 37.706604725423119),
    new GeoPosition(-122.36434936523438, 37.712059855877314),
    new GeoPosition(-122.43576049804686, 37.7524152343544)
});

GeoPolygon taipeiPolygon = new GeoPolygon(new[]
{
    new GeoPosition(121.56, 25.04),
    new GeoPosition(121.565, 25.04),
    new GeoPosition(121.565, 25.045),
    new GeoPosition(121.56, 25.045),
    new GeoPosition(121.56, 25.04)
});

// Search coffee shop in Both polygons, return results in en-US
Response<SearchAddressResult> searchResponse = await client.SearchInsideGeometryAsync("coffee", new GeoCollection(new[] { sfPolygon, taipeiPolygon }), new SearchInsideGeometryOptions
{
    Language = SearchLanguage.EnglishUsa
});

// Get Taipei Cafe and San Francisco cafe and print first place
SearchAddressResultItem taipeiCafe = searchResponse.Value.Results.Where(addressItem => addressItem.SearchAddressResultType == "POI" && addressItem.Address.Municipality == "Taipei City").First();
SearchAddressResultItem sfCafe = searchResponse.Value.Results.Where(addressItem => addressItem.SearchAddressResultType == "POI" && addressItem.Address.Municipality == "San Francisco").First();

Console.WriteLine("Possible Coffee shop in the Polygons:");
Console.WriteLine("Coffee shop address in Taipei: {0}", taipeiCafe.Address.FreeformAddress);
Console.WriteLine("Coffee shop address in San Francisco: {0}", sfCafe.Address.FreeformAddress);

検索アドレスの例

Response<SearchAddressResult> searchResult = await client.SearchAddressAsync("Seattle");

SearchAddressResultItem resultItem = searchResult.Value.Results[0];
Console.WriteLine("First result - Coordinate: {0}, Address: {1}",
    resultItem.Position, resultItem.Address.FreeformAddress);

トラブルシューティング

全般

Azure Maps サービスと対話すると、言語サービスによって返されるエラーは、REST API 要求に対して返されるのと同じ HTTP 状態コードに対応します。

たとえば、無効な座標で検索しようとすると、"Bad Request"400 を示すエラーが返されます。

次の手順

共同作成

このライブラリのビルド、テスト、および投稿の詳細については、 CONTRIBUTING.md を参照してください。

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「cla.microsoft.com>」を参照してください<。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。

インプレッション数