본문 바로가기
개발/Android

[Android] Google Maps API - 사용하기 2

by blacktree 2022. 10. 1.
반응형
 

[Android] Google Maps API - 사용하기 1

안드로이드에서 구글맵을 사용하기 위해서는 Google Maps API에 등록을 해야 합니다. 우선 구글맵 사용하기 전에 Google Maps API를 등록하는 방법부터 확인해보겠습니다. 목차 프로젝트 만들기 API 라이

blacktrees.tistory.com

 

안드로이드에서 구글맵을 사용하기 위해서는 Google Maps API에 등록한 API 키를 프로젝트에 적용해보겠습니다.

 

목차

  1. 프로젝트에 키 등록
  2. 레이아웃에 View 적용
  3. View 선언하여 사용

 

1) 프로젝트에 키 등록

  1. app build.gradle에 Google Play Services 라이브러리를 추가해준다.
  2. 추가해 준 후 , Sync Now를 선택한다.
  3. AndroidManifest에 아래와 같이 등록해준다.

build.gradle

implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:18.0.0'

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.test">

    <application
     ...>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API키" />

        <activity
            ...>
        </activity>
    </application>
</manifest>

2) 레이아웃에 View 적용

  1. map view를 적용할 레이아웃에 아래와 같이 적용한다.
<fragment android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.google.android.gms.maps.SupportMapFragment"/>

 3) View 선언하여 사용

  1. 아래와 같이 선언하여 사용한다.

activity

getSupportFragmentManager().findFragmentById(R.id.map).getMapAsync(this)

fragment

var smallMap : GoogleMap?= null
val fragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
fragment.getMapAsync(onSmallMapReadyCallback)
val onSmallMapReadyCallback =  object : OnMapReadyCallback {
    override fun onMapReady(googleMap: GoogleMap?) {
        smallMap = googleMap
        val location = getCurrentLocation()
        if (location != null){
            latLng = LatLng(location!!.latitude, location!!.longitude)
            val markerOptions = MarkerOptions()
            markerOptions.position(latLng)
            smallMap!!.addMarker(markerOptions)
            smallMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f))
        }
    }
}

728x90
반응형

댓글