본문 바로가기
프로그래밍/Android

[Android] 카카오맵 API 현재위치 구하는 코드

by Youngs_ 2022. 9. 18.
binding.nowLocation.setOnClickListener(){
    val permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
    if(permissionCheck == PackageManager.PERMISSION_GRANTED) {
        val lm: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        try {
            val userNowLocation: Location =
                lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)!!
            val uLatitude = userNowLocation.latitude
            val uLongitude = userNowLocation.longitude
            val uNowPosition = MapPoint.mapPointWithGeoCoord(uLatitude, uLongitude)
            mapView.setMapCenterPoint(uNowPosition, true)
        }catch(e: NullPointerException){
            Log.e("LOCATION_ERROR", e.toString())
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                ActivityCompat.finishAffinity(this)
            }else{
                ActivityCompat.finishAffinity(this)
            }

            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            System.exit(0)
        }
    }else{
        Toast.makeText(this, "위치 권한이 없습니다.", Toast.LENGTH_SHORT).show()
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE )
    }
}

댓글