次の方法で共有


Azure Maps .NET 用ルーティング クライアント ライブラリ - バージョン 1.0.0-beta.2

Azure Mapsルーティングは、場所または目的地へのルートを検索できるライブラリです。

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

作業の開始

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

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

dotnet add package Azure.Maps.Routing --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 MapsRoutingClient that will authenticate through Subscription Key (Shared key)
AzureKeyCredential credential = new AzureKeyCredential("<My Subscription Key>");
MapsRoutingClient client = new MapsRoutingClient(credential);

Azure AD 認証

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

AAD 認証を使用するには、「 Azure Identity README 」の説明に従って環境変数を設定し、 で使用するインスタンスを作成 DefaultAzureCredential します MapsRoutingClient

また、Azure Mapsクライアント ID も必要です。これは、Azure Active Directory 認証セクションの [Azure Maps] ページ>の [認証] タブ>の [クライアント ID] にあります。

AzureMapsPortal

// Create a MapsRoutingClient that will authenticate through Active Directory
TokenCredential credential = new DefaultAzureCredential();
string clientId = "<Your Map ClientId>";
MapsRoutingClient client = new MapsRoutingClient(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.Routing;
using Azure.Maps.Routing.Models;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Maps;
using Azure.ResourceManager.Maps.Models;

その後、 List Sas API を使用して SAS トークンを取得し、 に MapsRoutingClient割り当てることができます。 次のコード サンプルでは、特定のマップ アカウント リソースをフェッチし、コードの実行時に 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);
MapsRoutingClient client = new MapsRoutingClient(sasCredential);

主要な概念

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

  • Azure Mapsエンドポイントと通信して、目的地または目的地へのルートを取得する
  • エンドポイントAzure Maps通信して、指定された燃料、エネルギー、時間、または距離の予算に基づいて起点から到達できる場所のセットを計算します
  • エンドポイントAzure Maps通信して、出発地と目的地の場所によって定義された一連のルートのルート概要のマトリックスを計算します

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

スレッド セーフ

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

その他の概念

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

使用例

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

ルート API を呼び出す前に、最初の を MapsRoutingClient インスタンス化します。 この例では、AAD を使用してクライアント インスタンスを作成します。

// Create a MapsRoutingClient that will authenticate through Active Directory
TokenCredential credential = new DefaultAzureCredential();
string clientId = "<Your Map ClientId>";
MapsRoutingClient client = new MapsRoutingClient(credential, clientId);

ルートの方向

場所へのルーティングの簡単な例を次に示します。

// Create origin and destination routing points
List<GeoPosition> routePoints = new List<GeoPosition>()
{
    new GeoPosition(123.751, 45.9375),
    new GeoPosition(123.791, 45.96875),
    new GeoPosition(123.767, 45.90625)
};

// Create Route direction query object
RouteDirectionQuery query = new RouteDirectionQuery(routePoints);
Response<RouteDirections> result = client.GetDirections(query);

// Route direction result
Console.WriteLine($"Total {0} route results", result.Value.Routes.Count);
Console.WriteLine(result.Value.Routes[0].Summary.LengthInMeters);
Console.WriteLine(result.Value.Routes[0].Summary.TravelTimeDuration);

// Route points
foreach (RouteLeg leg in result.Value.Routes[0].Legs)
{
    Console.WriteLine("Route path:");
    foreach (GeoPosition point in leg.Points)
    {
        Console.WriteLine($"point({point.Latitude}, {point.Longitude})");
    }
}

目的地へのルートの場合は、移動モード、ルートの種類、言語、その他のオプションを指定することもできます。

// Create origin and destination routing points
List<GeoPosition> routePoints = new List<GeoPosition>()
{
    new GeoPosition(123.751, 45.9375),
    new GeoPosition(123.791, 45.96875),
    new GeoPosition(123.767, 45.90625)
};

RouteDirectionOptions options = new RouteDirectionOptions()
{
    RouteType = RouteType.Fastest,
    UseTrafficData = true,
    TravelMode = TravelMode.Bicycle,
    Language = RoutingLanguage.EnglishUsa,
};

// Create Route direction query object
RouteDirectionQuery query = new RouteDirectionQuery(routePoints);
Response<RouteDirections> result = client.GetDirections(query);

// Route direction result
Console.WriteLine($"Total {0} route results", result.Value.Routes.Count);
Console.WriteLine(result.Value.Routes[0].Summary.LengthInMeters);
Console.WriteLine(result.Value.Routes[0].Summary.TravelTimeDuration);

// Route points
foreach (RouteLeg leg in result.Value.Routes[0].Legs)
{
    Console.WriteLine("Route path:");
    foreach (GeoPosition point in leg.Points)
    {
        Console.WriteLine($"point({point.Latitude}, {point.Longitude})");
    }
}

詳細な例については、 ルート方向のサンプル ページを参照してください。

ルート マトリックス

複数の配信元と宛先の間のルート マトリックスを見つけるには、ルート マトリックス API Azure Mapsニーズに合わせる必要があります。 単純なルート マトリックス要求の例は、次のスニペットのようになります。

// A simple route matrix request
RouteMatrixQuery routeMatrixQuery = new RouteMatrixQuery
{
    // two origin points
    Origins = new List<GeoPosition>()
    {
        new GeoPosition(123.751, 45.9375),
        new GeoPosition(123.791, 45.96875)
    },
    // one destination point
    Destinations = new List<GeoPosition>() { new GeoPosition(123.767, 45.90625) },
};
Response<RouteMatrixResult> result = client.GetImmediateRouteMatrix(routeMatrixQuery);

非同期ルート マトリックス要求は次のようになります。 これは、データ ポイントがある origin * destination > 100 場合に便利です。

// Instantiate route matrix query
RouteMatrixQuery routeMatrixQuery = new RouteMatrixQuery
{
    // two origin points
    Origins = new List<GeoPosition>()
    {
        new GeoPosition(123.751, 45.9375),
        new GeoPosition(123.791, 45.96875)
    },
    // one destination point
    Destinations = new List<GeoPosition>() { new GeoPosition(123.767, 45.90625) },
};

// Instantiate route matrix options
RouteMatrixOptions routeMatrixOptions = new RouteMatrixOptions(routeMatrixQuery)
{
    TravelTimeType = TravelTimeType.All,
};

// Invoke an long-running operation route matrix request and directly wait for completion
GetRouteMatrixOperation result = client.GetRouteMatrix(WaitUntil.Completed, routeMatrixOptions);

詳細な例については、 ルート マトリックスのサンプル ページを参照してください。

ルート範囲

ルート範囲 API は、指定された燃料、エネルギー、時間、または距離の予算に基づいて、出発地から到達できる場所のセットを見つけるのに役立ちます。 ポリゴン境界 (または等時線) は、反時計回りの方向と、原点の結果である正確な多角形の中心で返されます。

// Search from a point of time budget that can be reached in 2000 seconds
RouteRangeOptions options = new RouteRangeOptions(123.75, 46)
{
    TimeBudget = new TimeSpan(0, 20, 0)
};
Response<RouteRangeResult> result = client.GetRouteRange(options);

詳細な例については、 ルート範囲のサンプル ページを参照してください。

トラブルシューティング

全般

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

たとえば、間違ったルーティング ポイントを渡すと、"Bad Request" (HTTP 400) を示すエラーが返されます。

try
{
    // An empty route points list
    List<GeoPosition> routePoints = new List<GeoPosition>() { };
    RouteDirectionQuery query = new RouteDirectionQuery(routePoints);

    Response<RouteDirections> result = client.GetDirections(query);
    // Do something with result ...
}
catch (RequestFailedException e)
{
    Console.WriteLine(e.ToString());
}

次の手順

  • その他のコンテキストと追加のシナリオについては、詳細なサンプルに関するページを参照してください。

共同作成

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

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

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

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

インプレッション数