Android용 Maps SDK 빠른 시작

Android 스튜디오용 Google 지도 템플릿을 사용하여 지도를 표시하는 Android 앱을 만듭니다. 설정할 기존 Android 스튜디오 프로젝트가 있는 경우에는 프로젝트 구성을 참고하세요.

이 빠른 시작은 자바 또는 Kotlin을 사용한 기본 Android 개발에 익숙한 개발자를 대상으로 합니다.

개발 환경 설정하기

  1. Android 스튜디오 Arctic Fox 이상이 필요합니다. 아직 다운로드하지 않은 경우 다운로드하고 설치하세요.
  2. Android 스튜디오에서 Android Gradle 플러그인 버전 7.0 이상을 사용 중이어야 합니다.

Android 기기 설정하기

Android용 Maps SDK를 사용하는 앱을 실행하려면 Google API를 포함하는 Android 4.0 이상의 Android 기기 또는 Android Emulator에 Android용 Maps SDK를 배포해야 합니다.

  • Android 기기를 사용하려면 하드웨어 기기에서 앱 실행의 안내를 따르세요.
  • Android Emulator를 사용하려면 Android 스튜디오와 함께 제공되는 Android Virtual Device(AVD) Manager를 이용해 가상 기기를 만들고 에뮬레이터를 설치할 수 있습니다.

Android 스튜디오에서 Google 지도 프로젝트 만들기

  1. Android 스튜디오를 열고 Welcome to Android Studio 창에서 Create New Project를 클릭합니다.

  2. New Project 창의 Phone and Tablet 카테고리에서 Google Maps Activity를 선택하고 Next를 클릭합니다.

  3. Google Maps Activity 양식을 작성합니다.

    • Language를 자바 또는 Kotlin으로 설정합니다. 두 언어 모두 Android용 Maps SDK에서 완벽하게 지원됩니다. Kotlin에 관한 자세한 내용은 Kotlin을 사용한 Android 앱 개발을 참고하세요.

    • Minimum SDK를 테스트 기기와 호환되는 SDK 버전으로 설정합니다. Android용 Maps SDK 버전 18.0.x, Android API 수준 19(Android 4.4, KitKat) 이상에 필요한 최소 버전보다 높은 버전을 선택해야 합니다. SDK 버전 요구사항에 대한 최신 정보는 출시 노트를 참고하세요.

  4. Finish를 클릭합니다.

    Android 스튜디오가 Gradle을 시작하고 프로젝트를 빌드합니다. 다소 시간이 걸릴 수 있습니다.

  5. 빌드가 완료되면 Android 스튜디오에서 AndroidManifest.xmlMapsActivity 파일을 엽니다. 활동은 이름이 다를 수는 있지만 설정 중에 구성한 활동입니다.

  6. AndroidManifest.xml 파일에는 Google 지도 API 키를 가져온 다음 local.properties 파일에 추가하는 방법에 대한 안내가 포함되어 있습니다. API 키를 AndroidManifest.xml 파일에 추가하지 마세요. 그렇게 하면 API 키가 안전하지 못한 방식으로 저장됩니다. 대신 다음 섹션의 안내에 따라 Cloud 프로젝트를 만들고 API 키를 구성합니다.

Google Cloud 프로젝트 설정

다음 탭을 차례로 클릭하여 필요한 Cloud 콘솔 설정 단계를 완료합니다.

1단계

콘솔

  1. Google Cloud 콘솔의 프로젝트 선택기 페이지에서 프로젝트 만들기를 클릭하여 새 Cloud 프로젝트를 만듭니다.

    프로젝트 선택기 페이지로 이동

  2. Cloud 프로젝트에 결제가 사용 설정되어 있어야 하므로 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

    Google Cloud에서는 0.00달러의 무료 체험판을 제공합니다. 무료 체험판은 90일 후 또는 계정에서 300달러에 해당하는 누적 비용이 발생한 시점 중 더 빠른 시점에 만료됩니다. 취소는 언제든지 가능합니다. Google Maps Platform에서는 매월 200달러의 월간 크레딧을 제공합니다. 자세한 내용은 결제 계정 크레딧결제를 참고하세요.

Cloud SDK

gcloud projects create "PROJECT"

Google Cloud SDK, Cloud SDK 설치 및 다음 명령어에 대해 자세히 알아보세요.

2단계

Google Maps Platform을 사용하려면 프로젝트에 사용할 API 또는 SDK를 사용 설정해야 합니다.

콘솔

Android용 Maps SDK 사용 설정

Cloud SDK

gcloud services enable \
    --project "PROJECT" \
    "maps-android-backend.googleapis.com"

Google Cloud SDK, Cloud SDK 설치 및 다음 명령어에 대해 자세히 알아보세요.

3단계

이 단계에서는 API 키만 만듭니다. 프로덕션에서 API 키를 사용하는 경우 API 키를 제한하는 것이 좋습니다. 자세한 내용은 제품별 API 키 사용 페이지를 참고하세요.

API 키는 사용 및 결제 목적으로 프로젝트와 관련된 요청을 인증하는 고유 식별자입니다. 프로젝트에 연결된 API 키가 하나 이상 있어야 합니다.

API 키를 만들려면 다음 단계를 따르세요.

콘솔

  1. Google Maps Platform > 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보 페이지로 이동

  2. 사용자 인증 정보 페이지에서 사용자 인증 정보 만들기 > API 키를 클릭합니다.
    API 키 생성 완료 대화상자에 새로 만든 API 키가 표시됩니다.
  3. 닫기를 클릭합니다.
    새 API 키는 사용자 인증 정보 페이지의 API 키 아래 나열됩니다.
    (프로덕션에 사용하기 전에 API 키를 제한하세요.)

Cloud SDK

gcloud alpha services api-keys create \
    --project "PROJECT" \
    --display-name "DISPLAY_NAME"

Google Cloud SDK, Cloud SDK 설치 및 다음 명령어에 대해 자세히 알아보세요.

앱에 API 키 추가

이 섹션에서는 앱이 더욱 안전하게 참조할 수 있도록 API 키를 저장하는 방법을 설명합니다. API 키는 버전 제어 시스템에 체크인하면 안 되며, 프로젝트의 루트 디렉터리에 있는 local.properties 파일에 저장하는 것이 좋습니다. local.properties 파일에 관한 자세한 내용은 Gradle 속성 파일을 참고하세요.

이 작업을 간소화하려면 Android용 Secrets Gradle 플러그인을 사용하는 것이 좋습니다. 플러그인을 설치하여 API 키를 저장하는 방법은 다음과 같습니다.

  1. Android 스튜디오에서 프로젝트 수준 build.gradle 파일을 열고 다음 코드를 buildscript 아래 dependencies 요소에 추가합니다.
    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' version '2.0.1' apply false
    }
  2. 그런 다음 모듈 수준 build.gradle 파일을 열고 plugins 요소에 다음 코드를 추가합니다.
    id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
        
  3. 파일을 저장하고 프로젝트를 Gradle과 동기화합니다.
  4. 프로젝트 수준 디렉터리에서 local.properties를 열고 다음 코드를 추가합니다. YOUR_API_KEY를 API 키로 변경합니다.
    MAPS_API_KEY=YOUR_API_KEY
        
  5. 파일을 저장합니다.
  6. AndroidManifest.xml 파일에서 com.google.android.geo.API_KEY로 이동한 후 android:value attribute를 다음과 같이 업데이트합니다.
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="${MAPS_API_KEY}" />
        

참고: 위의 내용처럼, com.google.android.geo.API_KEY는 API 키의 권장 메타데이터 이름입니다. 이 이름의 키는 Android 플랫폼에서 Android용 Maps SDK 등 여러 Google 지도 기반 API를 인증하는 데 사용할 수 있습니다. 이전 버전과의 호환성을 위해 API에서는 com.google.android.maps.v2.API_KEY 이름도 지원합니다. 이 기존 이름을 사용하면 Android 지도 API v2만 인증할 수 있습니다. 애플리케이션에서는 API 키 메타데이터 이름을 하나만 지정할 수 있습니다. 두 개가 모두 지정되면 API에서 예외가 발생합니다.

코드 보기

템플릿에서 제공되는 코드를 살펴봅니다. 특히 Android 스튜디오 프로젝트에서 다음 파일을 살펴봅니다.

지도 활동 파일

지도 활동 파일은 앱의 기본 활동으로, 지도를 관리하고 표시하기 위한 코드를 포함합니다. 기본적으로 활동을 정의하는 파일의 이름은 MapsActivity.java로 지정되거나, Kotlin을 앱의 언어로 설정하는 경우에는 MapsActivity.kt로 지정됩니다.

지도 활동의 기본 요소는 다음과 같습니다.

  • SupportMapFragment 객체는 지도의 수명 주기를 관리하며 앱 UI의 상위 요소입니다.

  • GoogleMap 객체는 지도 데이터 및 뷰에 대한 액세스 권한을 제공합니다. Android용 Maps SDK의 기본 클래스입니다. 지도 객체 가이드에서 SupportMapFragment 객체와 GoogleMap 객체를 자세히 설명합니다.

  • moveCamera 함수는 오스트레일리아 시드니의 LatLng 좌표에 지도의 중심을 맞춥니다. 지도를 추가할 때 가장 먼저 구성해야 하는 설정은 지도 위치 및 카메라 설정(예: 보기 각도, 지도 방향, 확대/축소 수준)입니다. 자세한 내용은 카메라 및 뷰 가이드를 참고하세요.

  • addMarker 함수가 시드니 좌표에 마커를 추가합니다. 자세한 내용은 마커 가이드를 참고하세요.

지도 활동 파일에는 다음 코드가 포함됩니다.

자바


import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
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;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     *
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

      

Kotlin


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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

internal class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    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)
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions()
            .position(sydney)
            .title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

      

모듈 Gradle 파일

모듈 build.gradle 파일에는 Android용 Maps SDK에서 요구하는 다음과 같은 지도 종속 항목이 포함됩니다.

dependencies {
    implementation 'com.google.android.gms:play-services-maps:18.1.0'
    // ...
}

지도 종속 항목 관리에 대한 자세한 내용은 버전 관리를 참조하세요.

XML 레이아웃 파일

activity_maps.xml 파일은 앱 UI의 구조를 정의하는 XML 레이아웃 파일입니다. 이 파일은 res/layout 디렉터리에 있습니다. activity_maps.xml 파일은 다음 요소를 포함하는 프래그먼트를 선언합니다.

  • tools:context는 프래그먼트의 기본 활동을 지도 활동 파일에 정의된 MapsActivity로 설정합니다.
  • android:name은 프래그먼트의 클래스 이름을 지도 활동 파일에서 사용하는 프래그먼트 유형인 SupportMapFragment로 설정합니다.

XML 레이아웃 파일에는 다음 코드가 포함되어 있습니다.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    tools:context=".MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

앱 배포 및 실행하기

오스트레일리아 시드니를 중심으로 한 지도와 마커가 표시된 스크린샷

앱을 성공적으로 실행하면 다음 스크린샷에서처럼 중심에 오스트레일리아 시드니가 있고 시드니에 마커가 표시된 지도가 나타납니다.

앱을 배포하고 실행하려면 다음 안내를 따르세요.

  1. Android 스튜디오에서 Run 메뉴 옵션(또는 재생 버튼 아이콘)을 클릭하여 앱을 실행합니다.
  2. 기기를 선택하라는 메시지가 나타나면 다음 옵션 중 하나를 선택합니다.
    • 컴퓨터에 연결된 Android 기기를 선택합니다.
    • 또는 Launch emulator 라디오 버튼을 선택하고 설정한 가상 기기를 선택합니다.
  3. OK를 클릭합니다. Android 스튜디오에서 Gradle을 시작하여 앱을 빌드한 후 기기 또는 에뮬레이터에 결과를 표시합니다. 앱이 시작되기까지 몇 분 정도 걸릴 수 있습니다.

다음 단계

  • 지도 설정: 이 주제에서는 카메라 위치, 지도 유형, UI 구성요소, 동작 등 지도의 초기 설정 및 런타임 설정 방법을 설명합니다.

  • Android 앱에 지도 추가(Kotlin): 이 Codelab에서는 Android용 Maps SDK의 몇 가지 추가 기능을 보여주는 앱을 시연합니다.

  • Maps Android KTX 라이브러리 사용: 이 Kotlin 확장 프로그램(KTX) 라이브러리를 사용하면 Android용 Maps SDK를 사용하는 동안 여러 Kotlin 언어 기능을 활용할 수 있습니다.