Android kotlin GPS 위치 권한 및 주소 가져오기

hjseo-dev·2022년 1월 1일
0

Android

목록 보기
3/18
post-thumbnail

📍 GPS 위치 권한 가져오기

gradle 파일에 추가

build.gradle 에 구글 플레이 서비스에서 제공하는 API를 주입시켜줍니다.

// google map api & location
 implementation 'com.google.android.gms:play-services-maps:18.0.0'
implementation 'com.google.android.gms:play-services-location:19.0.0'

AndroidManifest.xml 권한 설정 코드 추가

Sync Projects를 완료하고나면 원하는 곳에 위치 API를 사용할 수 있다.

checkSelfPermission을 통해 ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION 권한이 있는지 런타임에 확인해주고 권한이 있으면 위치 서비스에 연결시켜주고 lastLocation을 통해 현재위치를 가져올 수 있다.

<!--    정확한 위치    -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--    대략적인 위치    -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

📍 위치 권한 체크 및 요청 함수

//변수 선언
private lateinit var fusedLocationClient: FusedLocationProviderClient

//등록
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

 //퍼미션 체크 및 권한 요청 함수
    @SuppressLint("MissingPermission")
    private fun checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    // Got last known location. In some rare situations this can be null.
                    var geocoder = Geocoder(this, Locale.KOREA)
                    if (location != null) {
                        Toast.makeText(
                            this,
                            "현재위치..." + location.latitude + " / " + location.longitude,
                            Toast.LENGTH_SHORT
                        ).show()
                     
                    }
                }
        } else {
            Toast.makeText(this, "위치권한이 없습니다..", Toast.LENGTH_SHORT).show()

        }
    }

📍 권한 요청 결과 처리

결과를 처리하기 위해 onRequestPermissionsResult 를 사용하여 requestCode로 구별해준다. 실패 시 수행되는 동작을 지정할 수 있다.

//퍼미션 응답 처리 코드 (선언)
private val multiplePermissionsCode = 100
    
//권한 요청 결과 처리 함수
@SuppressLint("MissingSuperCall")
override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            multiplePermissionsCode -> {
                if (grantResults.isNotEmpty()) {
                    for ((i, permission) in permissions.withIndex()) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            //권한 획득 실패시 동작
                            Toast.makeText(
                                this,
                                "The user has denied to $permission",
                                Toast.LENGTH_SHORT
                            ).show()
                            Log.i("TAG", "I can't work for you anymore then. ByeBye!")
                        } else {
                            gpsGranted = true
                        }
                    }
                }
            }
        }
    }

📍 GPS 현재 위치 주소 가져오기

💡 GeoCoder 사용하기

Geocoder를 사용해 사용자가 입력한 주소값의 위도 및 경도를 받아오는 것을 구현했다. 먼저 geocoder선언을 해준 후 위에서 받은 위/경도 값을 getfromLocation함수에 담아 가져오고 하나씩 " "으로 구분하여 도, 시, 군, 동 을 순서대로 꺼내온다.

//주소 초기화 
    var address: List<String> = listOf("서울특별시", "중구", "명동")
    
 // Got last known location. In some rare situations this can be null.
                    var geocoder = Geocoder(this, Locale.KOREA)
                    if (location != null) {
                        Toast.makeText(
                            this,
                            "현재위치..." + location.latitude + " / " + location.longitude,
                            Toast.LENGTH_SHORT
                        ).show()
                        
                        val addrList =
                            geocoder.getFromLocation(location.latitude, location.longitude, 1)

                        for (addr in addrList) {
                            val splitedAddr = addr.getAddressLine(0).split(" ")
                            address = splitedAddr
                        }
                        //경기도, 성남시, 분당구, 삼평동
                        textView.append("현재위치 : ${address[1]}, ${address[2]}, ${address[3]}, ${address[4]}")
                    }

위와 같이 현재 위치를 로컬 주소로 표시할 수 있다!

0개의 댓글