こちらのサイトのメロディーとともにお楽しみください。
正式なタイトルはVisual StudioのXamarinでAndroidアプリを作る(#6) Geocorderを使うです。
6回目となる今回は、Geocorderを使って住所から緯度・経度を取得してみます。今回もdeveloper.xamarin.comのレシピ、ほとんどそのままですが、日本の住所の与え方や若干補足説明があった方が良いかと思い書きます。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/geocodeButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/geocodeButtonText" />
<TextView
android:id="@+id/addressText"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
画面には、緯度・経度引きを起動するボタンと取得した情報を表示するテキストビューを配置します。
次にMainActivityのコードです。
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading;
using Android.Locations;
using System.Linq;
namespace Geocorder
{
[Activity(Label = "Geocorder", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
var button = FindViewById<Button>(Resource.Id.geocodeButton);
button.Click += (sender, e) => {
new Thread(new ThreadStart(() => {
var geo = new Geocoder(this);
//var addresses = geo.GetFromLocationName("50 Church St, Cambridge, MA", 1);
var addresses = geo.GetFromLocationName("東京都港区六本木5-11-16", 1);
RunOnUiThread(() => {
var addressText = FindViewById<TextView>
(Resource.Id.addressText);
addresses.ToList().ForEach((addr) => {
addressText.Append(addr.ToString() +
"\r\n\r\n");
});
});
})).Start();
};
}
}
}
Geocoder#GetFromLocationNameには、日本語の住所をそのまんま与えます。
RunOnUiThreadは内部で、Handler#postを呼んでいます。
実行結果
緯度・経度のほかに郵便番号や詳細な住所も取得していますね。
