【Kotlin入門】Androidアプリで住所から緯度・経度を取得する方法を徹底解説
この記事では、Kotlinを使用してAndroidアプリで住所(文字列)から緯度と経度を取得する方法を、実際のコード例とともに段階的に解説します。Geocoder APIを活用したジオコーディングの基本をマスターしましょう。
全体の流れ
今回作成するアプリは、ユーザーが入力した住所文字列をGeocoderクラスに渡し、対応する緯度・経度を画面に表示するシンプルなものです。処理の流れは以下の通りです。
- EditTextで住所を入力
- ボタン押下でバックグラウンドスレッド上でGeocoderを実行
- Handlerを通じて結果をメインスレッドに返しTextViewに表示
ステップ1:プロジェクトの新規作成
Android Studioを開き、「File」→「New Project」を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートは「Empty Activity」を選択し、言語はKotlinを指定してください。
ステップ2:レイアウトファイル(activity_main.xml)の編集
res/layout/activity_main.xmlに以下のコードを追加します。住所入力用のEditText、検索実行ボタン、結果表示用のTextViewを配置しています。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:id="@+id/textViewAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:text="Enter Address: " android:textAppearance="?android:attr/textAppearanceMedium" android:textStyle="bold" /> <EditText android:id="@+id/editTextAddress" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toEndOf="@+id/textViewAddress" android:singleLine="true" android:text="" /> <Button android:id="@+id/addressButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textViewAddress" android:layout_marginTop="50dp" android:layout_toEndOf="@+id/textViewAddress" android:text="Show Lat/Long" /> <TextView android:id="@+id/latLongTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toEndOf="@+id/textViewAddress" android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@android:color/background_dark" /> </RelativeLayout>
ステップ3:MainActivity.ktの実装
src/MainActivity.ktに以下のコードを記述します。ボタンがクリックされると、入力された住所をGeoCodingLocationクラスに渡し、結果はHandler経由で受け取ってTextViewに反映します。
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var addressButton: Button
private lateinit var textViewAddress: TextView
lateinit var textViewLatLong: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textViewAddress = findViewById(R.id.textViewAddress)
textViewLatLong = findViewById(R.id.latLongTV)
addressButton = findViewById(R.id.addressButton)
addressButton.setOnClickListener {
val editText = findViewById<EditText>(R.id.editTextAddress)
val address = editText.text.toString()
val locationAddress = GeoCodingLocation()
locationAddress.getAddressFromLocation(address, applicationContext,
GeoCoderHandler(this))
}
}
companion object {
private class GeoCoderHandler(private val mainActivity: MainActivity) : Handler() {
override fun handleMessage(message: Message) {
val locationAddress: String?
locationAddress = when (message.what) {
1 -> {
val bundle = message.data
bundle.getString("address")
}
else -> null
}
mainActivity.textViewLatLong.text = locationAddress
}
}
}
}ステップ4:GeoCodingLocation.ktクラスの作成
新しいKotlinクラス「GeoCodingLocation.kt」を作成し、以下のコードを追加します。ここが処理の核心部分で、GeocoderのgetFromLocationName()メソッドを使って住所から位置情報を取得しています。
import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import java.io.IOException
import java.util.*
class GeoCodingLocation {
private val TAG = "GeoCodeLocation"
fun getAddressFromLocation(
locationAddress: String,
context: Context, handler: Handler
) {
val thread = object : Thread() {
override fun run() {
val geoCoder = Geocoder(
context,
Locale.getDefault()
)
var result: String? = null
try {
val addressList = geoCoder.getFromLocationName(locationAddress, 1)
if (addressList != null && addressList.size > 0) {
val address = addressList.get(0) as Address
val sb = StringBuilder()
sb.append(address.latitude).append("\n")
sb.append(address.longitude).append("\n")
result = sb.toString()
}
} catch (e: IOException) {
Log.e(TAG, "Unable to connect to GeoCoder", e)
} finally {
val message = Message.obtain()
message.target = handler
message.what = 1
val bundle = Bundle()
result = ("Address: $locationAddress" +
"\n\nLatitude and Longitude: \n" + result)
bundle.putString("address", result)
message.data = bundle
message.sendToTarget()
}
}
}
thread.start()
}
}ステップ5:AndroidManifest.xmlへの権限追加
androidManifest.xmlに以下のコードを追加し、位置情報へのアクセス権限を宣言します。Geocoderを使用するにはACCESS_FINE_LOCATIONパーミッションが必要です。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q11"> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
アプリの実行と動作確認
それでは実際にアプリを実行してみましょう。Android端末をPCに接続していることを前提としています。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーのRunアイコンをクリックしてください。表示された選択肢から接続中のモバイルデバイスを選択すると、実機の画面にアプリが起動します。

住所を入力してボタンをタップすると、その場所の緯度・経度が画面に表示されます。Geocoderはネットワーク接続を必要とするため、実行時はインターネットに接続された環境でテストしてください。
-
【Android】現在地の緯度・経度を取得する方法をサンプルコード付きで解説
この記事では、Androidアプリで現在地の緯度(latitude)と経度(longitude)を取得する方法を、実際に動作するサンプルコードとともにわかりやすく解説します。位置情報の取得には LocationManager クラスを使用します。GPSがオフの場合に設定画面へ誘導するダイアログの表示や、実行時パーミッションのリクエスト処理もあわせて実装していきます。ステップ1:Android Studioで新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成してください。
-
Pythonで都市の緯度・経度を取得する方法|geopyライブラリの使い方を解説
都市の緯度と経度を取得したい場合、Pythonではgeopyモジュールが便利です。geopyは、サードパーティ製のジオコーダやさまざまなデータソースを利用して、住所・都市・国などの座標情報を特定できるライブラリです。 まず、geopyモジュールがインストールされていることを確認しましょう。未インストールの場合は、以下のコマンドでインストールできます。 pip install geopy 以下の例では、Nominatimというジオコーダを使用して、都市「ハイデラバード(Hyderabad)」の緯度と経度を取得します。 手順 geopyモジュールからNominatimジオコーダをインポートします