Android
안드로이드 현재 위치 위도, 경도 구하기 / 좌표 주소로 변환하기
hyerann
2019. 7. 16. 17:57
우선 Manifest에 필요한 permission을 추가한다.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
원하는 Activity에서 코드를 작성한다.
var locationManager : LocationManager? = null
private val REQUEST_CODE_LOCATION : Int = 2
var currentLocation : String = ""
var latitude : Double? = null
var longitude : Double? = null
private fun getCurrentLoc() {
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager?
var userLocation: Location = getLatLng()
if (userLocation != null) {
latitude = userLocation.latitude
longitude = userLocation.longitude
Log.d("CheckCurrentLocation", "현재 내 위치 값: $latitude, $longitude")
var mGeocoder = Geocoder(applicationContext, Locale.KOREAN)
var mResultList: List<Address>? = null
try {
mResultList = mGeocoder.getFromLocation(
latitude!!, longitude!!, 1
)
} catch (e: IOException) {
e.printStackTrace()
}
if (mResultList != null) {
Log.d("CheckCurrentLocation", mResultList[0].getAddressLine(0))
currentLocation = mResultList[0].getAddressLine(0)
currentLocation = currentLocation.substring(11)
}
}
}
private fun getLatLng() : Location {
var currentLatLng: Location? = null
if (ActivityCompat.checkSelfPermission(applicationContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), this.REQUEST_CODE_LOCATION)
getLatLng()
} else {
val locationProvider = LocationManager.GPS_PROVIDER
currentLatLng = locationManager?.getLastKnownLocation(locationProvider)
}
return currentLatLng!!
}
latitude, longitude에 위도, 경도 값이 저장되고, currentLocation에 좌표를 주소로 변환한 String 값이 저장된다.
앞에 '대한민국 서울특별시 '를 제외하기 위해 substring을 사용하여 문자열을 잘라냈고 이를 포함시키고 싶으면 해당 줄을 지우면 된다.