프로젝트 만들때 템플릿에서 Google Maps Activity선택!!
EmptyActivity와 다른점
1. 기본 layout이 Fragment로 설정되어있음
2. src폴더 내에 debug폴더가 생성되어있음
google_maps_api.xml
src > debug > res > values > google_maps_api.xml
1. https://developers.google.com/maps/documentation/android/start#get-key에 들어가기
2. Cloud Console에서 설정하기 > 3단계 Get an API Key 클릭
3. 사용자 인증 정보 페이지로 이동하기 클릭
4. 프로젝트 만들기
5. Mapss SDK for Android > 사용
6. 좌측 사용자 인증 정보 > + 사용자 인증 정보 만들기
7. 할당받은 API키 복사
<string name="google_maps_key" translatable="false" templateMergeStrategy="preserve">복사한 API키 붙여넣기</string>
build.gradle !추가 (Sync now 해주기)
dependencies {
! implementation 'com.google.android.gms:play-services-location:17.1.0'
! implementation 'com.google.android.gms:play-services-maps:17.1.0'
...
}
MapsActivity
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) {
mMap = 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())
setLocation(37.4923219, 126.91161889999998)
}
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))
}
}
'Kotlin' 카테고리의 다른 글
[Kotlin] 가위바위보 (0) | 2022.02.22 |
---|---|
[kotlin] 2 (0) | 2022.02.09 |
[Kotlin] (0) | 2022.02.03 |
댓글