Android
 Computer >> コンピューター >  >> プログラミング >> Android

Android Kotlinで緯度・経度から完全な住所を取得する方法【Geocoder活用ガイド】

この記事では、Androidアプリ開発においてGeocoder APIを活用し、緯度と経度から完全な住所を取得する方法(リバースジオコーディング)を、ステップ形式でわかりやすく解説します。位置情報パーミッションの処理や、UIスレッドへの結果表示など、実践的なポイントもあわせて紹介します。

ステップ1:Android Studioで新規プロジェクトを作成する

まずはAndroid Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトのセットアップを完了させましょう。

ステップ2:res/layout/activity_main.xml に以下のコードを追加する

メイン画面のレイアウトには、ボタンと住所を表示するための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="16sp"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/btnShowAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Show Address" />
    <TextView
        android:id="@+id/tvAddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnShowAddress"
        android:layout_centerInParent="true"
        android:textColor="@android:color/background_dark"
        android:textSize="12sp"
        android:textStyle="bold" />
</RelativeLayout>

ステップ3:src/MainActivity.kt に以下のコードを追加する

MainActivityでは、位置情報パーミッションのリクエスト処理、ボタンクリック時の住所取得処理、そして設定画面への遷移ダイアログを実装します。

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
    lateinit var btnShowAddress: Button
    lateinit var tvAddress: TextView
    lateinit var location: Location
    lateinit var appLocationService: AppLocationService
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        tvAddress = findViewById(R.id.tvAddress)
        appLocationService = AppLocationService(this)
        btnShowAddress = findViewById(R.id.btnShowAddress)
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
        }
        btnShowAddress.setOnClickListener {
            location = appLocationService.getLocation(LocationManager.GPS_PROVIDER)!!
            val latitude = 13.1000727
            val longitude = 80.2126274
            val locationAddress = LocationAddress()
            locationAddress.getAddressFromLocation(
                latitude, longitude, applicationContext, GeoCodeHandler()
            )
            showSettingsAlert()
        }
    }
    private fun showSettingsAlert() {
        val alertDialog = AlertDialog.Builder(this)
        alertDialog.setTitle("SETTINGS")
        alertDialog.setMessage("Enable Location Provider! Go to settings menu?")
        alertDialog.setPositiveButton("Settings") { _, _ ->
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            this@MainActivity.startActivity(intent)
        }
        alertDialog.setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() }
        alertDialog.show()
    }
    internal inner class GeoCodeHandler : Handler() {
        override fun handleMessage(message: Message) {
            val locationAddress: String = when (message.what) {
                1 -> {
                    message.data.getString("address").toString()
                }
                else -> null.toString()
            }
            tvAddress.text = locationAddress
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
                }
                return
            }
        }
    }
}

ステップ4:AppLocationService.kt を新規作成する

Kotlinクラスとして「AppLocationService.kt」を作成し、以下のコードを記述します。このクラスはLocationManagerを通じて端末の現在地情報を取得する役割を担います。

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
open class AppLocationService(context: Context) : Service(),
LocationListener {
    private var locationManager: LocationManager? =
    context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    private lateinit var location: Location
    @SuppressLint("MissingPermission")
    fun getLocation(provider: String?): Location? {
        if (locationManager!!.isProviderEnabled(provider)) {
            locationManager!!.requestLocationUpdates(
            provider,
            MIN_TIME_FOR_UPDATE,
            MIN_DISTANCE_FOR_UPDATE.toFloat(), this
            )
            if (locationManager != null) {
                location = locationManager!!.getLastKnownLocation(provider)
                return location
            }
        }
        return null
    }
    override fun onLocationChanged(location: Location) {}
    override fun onProviderDisabled(provider: String) {}
    override fun onProviderEnabled(provider: String) {}
    override fun onStatusChanged(
    provider: String,
    status: Int,
    extras: Bundle
    ) {
    }
    override fun onBind(arg0: Intent): IBinder? {
        return null
    }
    companion object {
        private const val MIN_DISTANCE_FOR_UPDATE: Long = 10
        private const val MIN_TIME_FOR_UPDATE = 1000 * 60 * 2.toLong()
    }
}

ステップ5:LocationAddress.kt を新規作成する

次に「LocationAddress.kt」というKotlinクラスを作成し、以下のコードを追加します。ここが本記事の核となる部分で、Geocoderを使って緯度・経度を実際の住所文字列へ変換します。ネットワーク処理のため、別スレッド上で実行している点にも注目してください。

import android.content.Context
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 LocationAddress {
    private val tag = "LocationAddress"
    fun getAddressFromLocation(
    latitude: Double,
    longitude: Double, context: Context, handler: Handler
    ) {
        val thread = object : Thread() {
            override fun run() {
                val geoCoder = Geocoder(
                context,
                Locale.getDefault()
                )
                var result: String = null.toString()
                try {
                    val addressList = geoCoder.getFromLocation(
                    latitude, longitude, 1
                    )
                    if ((addressList != null && addressList.size > 0)) {
                        val address = addressList.get(0)
                        val sb = StringBuilder()
                        for (i in 0 until address.maxAddressLineIndex) {
                            sb.append(address.getAddressLine(i)).append("\n")
                        }
                        sb.append(address.locality).append("\n")
                        sb.append(address.postalCode).append("\n")
                        sb.append(address.countryName)
                        result = sb.toString()
                    }
                } catch (e: IOException) {
                    Log.e(tag, "Unable connect to GeoCoder", e)
                } finally {
                    val message = Message.obtain()
                    message.target = handler
                    message.what = 1
                    val bundle = Bundle()
                    result = ("Latitude: " + latitude + " Longitude: " + longitude +
                    "\n\nAddress:\n" + result)
                    bundle.putString("address", result)
                    message.data = bundle
                    message.sendToTarget()
                }
            }
        }
        thread.start()
    }
}

ステップ6:AndroidManifest.xml にパーミッションを追加する

最後に、マニフェストファイルに位置情報アクセス権限を宣言します。これを忘れるとアプリがクラッシュする原因となるため注意しましょう。

<?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(実行)」アイコンをクリックします。デバイス選択画面で自分のモバイル端末を選択すると、端末側にアプリの初期画面が表示されます。

ボタンをタップすると、指定した緯度・経度に対応する住所がTextView上に出力されます。GPSが無効になっている場合は、設定画面を開くよう促すダイアログが表示される仕組みです。

以上で、Kotlinを使った緯度・経度からの住所取得機能の実装は完了です。GeocoderはGoogle Play Servicesがインストールされた端末でのみ動作する点や、オフライン環境では例外が発生する点にも留意しながら、ぜひ自身のプロジェクトに応用してみてください。

  1. 【Android】現在地の緯度・経度を取得する方法をサンプルコード付きで解説

    この記事では、Androidアプリで現在地の緯度(latitude)と経度(longitude)を取得する方法を、実際に動作するサンプルコードとともにわかりやすく解説します。位置情報の取得には LocationManager クラスを使用します。GPSがオフの場合に設定画面へ誘導するダイアログの表示や、実行時パーミッションのリクエスト処理もあわせて実装していきます。ステップ1:Android Studioで新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成してください。

  2. Android端末のメインメールアドレスを取得する方法をサンプルコード付きで解説

    本記事では、Android端末に登録されているメインのメールアドレスを取得する方法を、実際のサンプルコードとともにわかりやすく解説します。AccountManagerとGET_ACCOUNTS権限を活用することで、端末に設定されたアカウント情報からメールアドレスを取得できます。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを起動し、「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。 手順2:res/layout/activity_main.xml にコードを追加する 以下のコードをレイアウト