MapLocationFinderResultクラスのFindLocationAsyncメソッドを使用すると、住所から緯度と経度を求めることができます。
住所から緯度と経度を求めることをジオコーディングと呼びます。
今回のコードを実行する前に、MainPage.xamlを以下のように編集します。
画面上部には、検索する住所を入力できるTextBox、検索を開始するためButton、求めた緯度と経度を表示するTextBlockを配置します。
また、画面上にMapControlを1つ配置します。
<StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <TextBox x:Name="txtAddress" TextWrapping="Wrap" Text="" Width="381"/> <Button x:Name="btnGetLocation" Content="現在値の取得" HorizontalAlignment="Left" VerticalAlignment="Stretch" Width="120" Click="btnGetLocation_Click" /> <TextBlock x:Name="txbPos" TextWrapping="Wrap" Text=""/> </StackPanel> <Maps:MapControl x:Name="mapControl1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0" Width="500" Height="500" ZoomInteractionMode="GestureAndControl" TiltInteractionMode="GestureAndControl" MapServiceToken="取得済みのキー" /> </StackPanel>
続いて、Buttonが押されたときに、TextBoxに入力されている住所から緯度と経度を求めるコードを入力します。
private async void btnGetLocation_Click(object sender, RoutedEventArgs e) { // ①TextBoxに入力されている住所を取得 string addressToGeocode = txtAddress.Text; // ②現在 MapControlの中心に表示されている緯度と経度を取得しGeoPointを作成する BasicGeoposition queryHint = new BasicGeoposition(); queryHint.Latitude = mapControl1.Center.Position.Latitude; queryHint.Longitude = mapControl1.Center.Position.Longitude; Geopoint hintPoint = new Geopoint(queryHint); // ③住所を元に緯度と経度を求める MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync( addressToGeocode, hintPoint, 3); // ④住所から緯度と経度の取得が成功したか if (result.Status == MapLocationFinderStatus.Success) { // TextBlockに検索結果の緯度と経度を表示する txbPos.Text = "result = (" + result.Locations[0].Point.Position.Latitude.ToString() + "," + result.Locations[0].Point.Position.Longitude.ToString() + ")"; // ⑤MapControlの中心を、検索結果の位置に設定する mapControl1.Center = result.Locations[0].Point; } }
①は、TextBoxに入力されている住所を変数に格納しています。
②は、MapControlの現在の中心位置の緯度と経度を取得しています。個々で取得した緯度と経度は、検索時の起点となる位置とします(③で使用します)。
③はFindLocationAsyncメソッドを使用して、住所から位置情報を取得します。第1引数は住所を表す文字列を、第2引数は検索を開始する地理的な場所をセットします(②で作成した位置)、第3引数は返される位置情報の最大数です。
④は、検索が成功したかどうかをチェックしています。取得結果はresul.Locationsで取得することができます。ここからLatitudeとLongtitudeを取得します。
⑤は、検索した緯度と経度を、MapControlの中心に設定しています。
以下に、東京都庁の住所を入力して検索をしてみた実行例を示します。
Please follow and like us:
コメント