Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Javscript
- stylesheet
- Java
- RecyclerView
- Kotlin
- JS
- 스프링부트
- React
- fragment
- scrollview
- TextView
- Linux
- button
- Hook
- GoogleMaps
- Android
- 안드로이드
- TypeScript
- 코틀린
- 자바스크립트
- 오버라이딩
- 랜덤번호
- nodejs
- SpringBoot
- 랜덤넘버
- npm
- array
- 구글맵스
- 리액트
- JavaScript
Archives
- Today
- Total
타닥타닥 개발자의 일상
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))
}*/
}
위의 코드를 실행하면 콘솔창에 자신의 위치가 출력된다.
'코딩 기록 > Kotlin' 카테고리의 다른 글
Kotlin 코틀린 저장된 사진 불러와서 안드로이드 화면에 구현하기 / File (0) | 2022.02.17 |
---|---|
코틀린 kotlin 구글 맵스 이용하여 위도,경도 주소로 바꾸기 / 위도,경도 주소로 바꾸기 하는 안드로이드 화면 만들기 (0) | 2022.02.16 |
Kotlin 코틀린 안드로이드 화면에 카메라 연결하고 촬영하기, 촬영된 사진 및 저장된 사진 불러와서 화면에 연결하기 (2) | 2022.02.16 |
Kotlin 코틀린 RecycleView, DatePicker, Singleton, SQLlite 사용해서 안드로이드 가계부 만들기 (0) | 2022.02.15 |
kotlin 코틀린 sqllite로 데이터 입력,삭제,조회하는 안드로이드 프로그램 만들기 (0) | 2022.02.12 |
Comments