場所を検索して地図アプリで表示させる
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/etSearchWord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btMapSearch"
android:text="地図検索" />
</LinearLayout>
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val btMapSearch = findViewById<Button>(R.id.btMapSearch)
btMapSearch.setOnClickListener{
onMapSearchButtonClick()
}
}
private fun onMapSearchButtonClick() {
// 検索ワードのURLエンコード
val etSearchWord = findViewById<EditText>(R.id.etSearchWord)
var searchWord = etSearchWord.text.toString()
// URLエンコーディング(「?」とか「&」などの文字を「%xxx」に直す) ※1
searchWord = URLEncoder.encode(searchWord, "UTF-8")
// URI文字列からURIオブジェクトにする("geo:緯度,経度?q=...)
val uri = Uri.parse("geo:0,0?q=${searchWord}")
// intentオブジェクトの生成
val intent = Intent(Intent.ACTION_VIEW, uri) ※2
// アクティビティの起動
startActivity(intent)
}
}
※1 … URLは半角英数字とハイフンなどの一部記号しか使えません。それ以外の文字をURLに使いたい場合はURLエンコードします。URLエンコードとは、URLとして使用できない文字を%xxという16進数のコードに直す作業です。KotlinではURLEncoderクラスのencodeメソッドを使います。
※2 … ACTOIN_VIEWは画面を表示させる、ACTION_CALLは電話をかける、ACTION_SENDはメールを送信する
BACK