前提
Kotlinで、現在地の天気がわかる天気予報アプリを制作しています。
現在地が分かるように、その場所の緯度と経度を知る必要があります。
そこで緯度と経度を取得しようとしているのですが、デベロッパーを読んでも分かりません。
実現したいこと
- 緯度と経度を取得したい
該当のソースコード
MainActivity.kt
1import android.Manifest 2import android.content.ContentValues.TAG 3import android.content.pm.PackageManager 4import androidx.appcompat.app.AppCompatActivity 5import android.os.Bundle 6import android.util.Log 7import android.widget.Toast 8import androidx.core.app.ActivityCompat 9import androidx.core.content.ContextCompat 10import androidx.lifecycle.lifecycleScope 11import com.example.weatherapp.databinding.ActivityMainBinding 12import com.google.android.gms.location.FusedLocationProviderClient 13import com.google.android.gms.location.LocationServices 14import kotlinx.coroutines.Dispatchers 15import kotlinx.coroutines.launch 16import kotlinx.coroutines.withContext 17 18 19class MainActivity : AppCompatActivity() { 20 21 private lateinit var binding: ActivityMainBinding 22 private lateinit var fusedLocationClient: FusedLocationProviderClient 23 24 override fun onCreate(savedInstanceState: Bundle?) { 25 super.onCreate(savedInstanceState) 26 binding = ActivityMainBinding.inflate(layoutInflater) 27 setContentView(binding.root) 28 29 locationDialog() 30 31 lifecycleScope.launch { 32 withContext(Dispatchers.IO) { 33 getCurrentLocation() 34 } 35 } 36 } 37 38 override fun onRequestPermissionsResult( 39 40 41 requestCode: Int, 42 permissions: Array<out String>, 43 grantResults: IntArray 44 ) { 45 super.onRequestPermissionsResult(requestCode, permissions, grantResults) 46 47 if (requestCode == 100) { 48 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 49 Toast.makeText(this, "位置情報にアクセスを許可されました", Toast.LENGTH_SHORT).show() 50 51 } else { 52 Toast.makeText(this, "設定から位置情報にアクセスを許可してください", Toast.LENGTH_SHORT).show() 53 } 54 } 55 } 56 57 58 private fun locationDialog() { 59 //パーミッションの状態確認 60 61 //位置情報許可されている 62 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 63 Log.d(TAG, "位置情報許可されています") 64 //位置情報許可されていない 65 } else { 66 Log.d(TAG, "位置情報許可されていないのでバーミッションダイアログを表示しました。") 67 //パーミッションダイアログ表示 68 ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 100) 69 } 70 } 71 72 private fun getCurrentLocation() { 73 //緯度経度取得 74 fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) 75 76 77 } 78}
試したこと
デベロッパーのコードの通りに進めたが、getLastLocation()をどのように使ったらいいのかわからなかった
https://developer.android.com/training/location/retrieve-current?hl=ja#last-known
補足情報(FW/ツールのバージョンなど)
・今回はACCESS_COARSE_LOCATIONを使用しています。
・getCurrentLocationに緯度と経度を取得するコードを書きたいです。
公式サイト
https://developer.android.com/training/location/retrieve-current?hl=ja#last-known
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。