타닥타닥 개발자의 일상

kotlin 코틀린 구글맵스 이용하여 자신의 위치 gps로 추적하기, 자신의 위치 위도 경도로 표시하기 본문

코딩 기록/Kotlin

kotlin 코틀린 구글맵스 이용하여 자신의 위치 gps로 추적하기, 자신의 위치 위도 경도로 표시하기

NomadHaven 2022. 2. 16. 22:32

 

새로운 프로젝트에서 Google Maps Activity 생성.

 

 

 

 

AndroidManinfest.xml에 아래의 코드 삽입하고 Sync Now 누르기.

인터넷과 위치 추적 허용해주는 코드

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

 

아래는 코드 적용된 전체 코드

 

 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.myapplication">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the "MyLocation" functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.MyApplication">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="@string/google_maps_key"/>

        <activity
                android:name=".MapsActivity"
                android:exported="true"
                android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

google_maps_api.xml
<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=03:9A:AB:2D:83:50:C0:32:AE:95:2C:AC:D3:82:72:47:B0:D9:15:CE%3Bcom.example.myapplication

    You can also add your credentials to an existing key, using these values:

    Package name:
    com.example.myapplication

    SHA-1 certificate fingerprint:
    03:9A:AB:2D:83:50:C0:32:AE:95:2C:AC:D3:82:72:47:B0:D9:15:CE

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key


    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" translatable="false" templateMergeStrategy="preserve">AIzaSyD_SLUKJXnyGEweAKXFxV7R2-yqDn7xUF0</string>
</resources>

 

MapsActivity.kt

 

 

package com.example.myapplication

import android.Manifest
import android.annotation.SuppressLint
import android.location.Location
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.databinding.ActivityMapsBinding
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityMapsBinding

    lateinit var locationPermission: ActivityResultLauncher<Array<String>>


    //위치 서비스가 gps를 사용해서 위치를 확인
    lateinit var fusedLocationClient: FusedLocationProviderClient

    //위치 값 요청에 대한 갱신 정보를 받는 변수
    lateinit var locationCallback: LocationCallback


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

       locationPermission = registerForActivityResult(
           ActivityResultContracts.RequestMultiplePermissions()){ results ->
           if(results.all{it.value}){
               startProcess()
           }else{ //문제가 발생했을 때
               Toast.makeText(this,"권한 승인이 필요합니다.",Toast.LENGTH_LONG).show()
           }
       }

        //권한 요청
        locationPermission.launch(
            arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        )
    }

    fun startProcess(){
        //구글 맵을 준비하는 작업을 진행한다
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync (this)

    }

    override fun onMapReady(googleMap: GoogleMap) {

      fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
       updateLocation()


    }

    @SuppressLint("MissingPermission")
    fun updateLocation(){
        val locationRequest = LocationRequest.create()
        locationRequest.run{
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            interval = 1000
        }

        locationCallback = object :LocationCallback(){
            //1초에 한번씩 변경된 위치 정보가 onLocationResult 으로 전달된다.
            override fun onLocationResult(locationResult: LocationResult?) {
             locationResult?.let{
                 for (location in it.locations){
                      Log.d("위치정보",  "위도: ${location.latitude} 경도: ${location.longitude}")
                   //   setLastLocation(location) //계속 실시간으로 위치를 받아오고 있기 때문에 맵을 확대해도 다시 줄어든다.

                    }
                }
            }
        }
        //권한 처리
        fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback,Looper.myLooper())

    }

    fun setLastLocation(lastLocation: Location){
        val LATLNG = LatLng(lastLocation.latitude,lastLocation.longitude)

        val makerOptions = MarkerOptions().position(LATLNG).title("I am here")
        val cameraPosition = CameraPosition.Builder().target(LATLNG).zoom(15.0f).build()

        mMap.clear()
        mMap.addMarker(makerOptions)
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))


    }

    //본인이 설정한 위도, 경도를 적용하는 경우

/*    fun setLocation(latitude:Double,longitude:Double){
        val LATLNG = LatLng(latitude,longitude)

        val makerOptions = MarkerOptions().position(LATLNG).title("I am here")
        val cameraPosition = CameraPosition.Builder().target(LATLNG).zoom(15.0f).build()

        mMap.clear()
        mMap.addMarker(makerOptions)
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))

    }*/


}

 

 

 

위의 코드를 실행하면 콘솔창에 자신의 위치가 출력된다.

 

Comments