Android
[Android] 현재 내 위치 가져오는 법
참깨빵위에참깨빵_
2024. 11. 13. 19:05
728x90
반응형
※ 모든 코드는 예시 코드기 때문에 사용하려면 반드시 예외처리, 리팩토링 후 사용한다
libs.version.toml 파일에 라이브러리를 하나 추가하고 앱 gradle에 적용한다.
[versions]
playServicesLocation = "21.3.0"
[libraries]
play-services-location = { module = "com.google.android.gms:play-services-location", version.ref = "playServicesLocation" }
implementation(libs.play.services.location)
그리고 매니페스트에 권한을 추가한다.
<!-- Always include this permission -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Include only if your app benefits from precise location access. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
액티비티 파일은 아래와 같이 작성한다.
import android.Manifest
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.locationtestapp.databinding.ActivityMainBinding
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var binding: ActivityMainBinding
private val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
getCurrentLocation()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
enableEdgeToEdge()
ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
requestLocationPermission()
}
private fun requestLocationPermission() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
} else {
getCurrentLocation()
}
}
private fun getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val latitude = it.latitude
val longitude = it.longitude
binding.tvLocation.text = getAddressFromLocation(latitude, longitude)
}
}
}
}
private fun getAddressFromLocation(latitude: Double, longitude: Double): String {
val geocoder = Geocoder(this, Locale.getDefault())
val addresses = geocoder.getFromLocation(latitude, longitude, 1)
if (!addresses.isNullOrEmpty()) {
val address = addresses[0]
val city = address.adminArea // OO시
val district = address.subLocality // OO구
val neighborhood = address.thoroughfare // OO동
return "$city $district $neighborhood"
} else {
return "something is wrong!"
}
}
}
이렇게 하면 getAddressFromLocation()의 리턴값으로 OO시 OO구 OO동이라는 문자열을 받게 된다. 얻은 문자열은 추가로 가공하거나 어딘가에 표시해서 사용하면 된다.
글 시작에 적어뒀듯 예시 코드기 때문에 사용하려면 반드시 필요한 예외처리와 리팩토링 후 사용하길 권장한다.
반응형