본문 바로가기
개발/안드로이드

[안드로이드]코틀린 : 구글 지도를 사용하는 방법

by 핸디(Handy) 2020. 6. 24.

갓 구글님이 이제 자바가 아닌 코틀린을 1언어로 지정함에 따라... 저도 따라갑니다. 그래서 이번 기회에 토이프로젝트를 진행하면서 구글지도관련된 포스트를 하나씩 완성해가겠습니다. 

간단하게 구글지도를 이용하려면 프로젝트 생성 단계에서 Google Maps Activity를 선택해줍니다.
그러면 거의 끝났습니다.

 

구글지도를 사용하기 위해선 다음과 같은 퍼미션이 필요합니다. 따라서

 

<AndroidManifest.xml> 

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

 

<MapsActivity.kt>

package com.dev.random_meal

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult

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.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap
    private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: MyLocationCallBack

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)

        initLocation()
    }


    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        val seoul = LatLng(37.715133, 126.734086)
        mMap.addMarker(MarkerOptions().position(seoul).title("Marker in Seoul"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul))
    }

    private fun initLocation(){
        fusedLocationProviderClient = FusedLocationProviderClient(this)

        locationCallback = MyLocationCallBack()

        locationRequest = LocationRequest()

        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        locationRequest.interval = 10000
        locationRequest.fastestInterval = 5000
    }

    override fun onResume() {
        super.onResume()
        addLocationListener()
    }

    private fun addLocationListener(){
        fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,null)

    }

    inner class MyLocationCallBack : LocationCallback(){
        override fun onLocationResult(locationResult: LocationResult?) {
            super.onLocationResult(locationResult)

            val location = locationResult?.lastLocation

            location?.run {
                val latLng = LatLng(latitude,longitude)
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,17f))
            }
        }
    }
}

전체적인 코드는 간단합니다. 

맵이 준비되면 ( onMapReady ) 마커를 찍고 (mMap.addMarker) 해당 좌표로 이동합니다 ( mMap.moveCamera )

그러한 와중에 디바이스의 위치가 변하면 ( MyLocationCallBack ) 해당 콜백으로 알려줘서 현재 위치를 조정합니다.

 


 

모든 코드는 이곳에서

 

gyeongseokKang/Random_Meal

init. Contribute to gyeongseokKang/Random_Meal development by creating an account on GitHub.

github.com

 

댓글