0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

位置情報を取得する方法のメモ

Posted at

Androidで位置情報を取得する方法とオプションをメモします。
Android で位置情報を取得するには、Fused Location Provider APIを利用するのがいいです。FusedLocationProviderClient を通じて現在地の取得・更新を簡単に実装できます。位置情報をリアルタイムで取得したい場合や、1回だけ取得したい場合など設定できます。

private lateinit var fusedLocationClient: FusedLocationProviderClient
private val locationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult) {
        super.onLocationResult(locationResult)

        for (location in locationResult.locations) {
            println( "位置を取得しました: 緯度${location.latitude}, 経度${location.longitude}")
        }
    }
}

val locationRequest = LocationRequest.Builder(
    Priority.PRIORITY_HIGH_ACCURACY, // 優先度の設定
    2000L // 更新間隔
).apply {
    setMinUpdateIntervalMillis(2000L) // 最小の更新間隔の設定
    setMaxUpdateDelayMillis(5000L) // 最小の更新間隔の設定
    setWaitForAccurateLocation(true) // 最小の更新間隔の設定
}.build()

fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext())

fusedLocationClient.requestLocationUpdates(
    locationRequest,
    locationCallback,
    Looper.getMainLooper()
)
// 位置を取得しました: 緯度xxx, 経度xxx
override fun onPause() {
    super.onPause()
    fusedLocationClient.removeLocationUpdates(locationCallback) // 位置情報取得を停止する。
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?