마커가 포함된 지도 추가

이 튜토리얼에서는 Android 앱에 Google 지도를 추가하는 방법을 설명합니다. 지도에는 특정 위치를 나타내는 마커(핀이라고도 함)가 포함됩니다.

튜토리얼에 따라 Android용 Maps SDK를 사용하여 Android 앱을 빌드하세요. 권장되는 개발 환경은 Android 스튜디오입니다.

코드 가져오기

GitHub에서 Google Maps Android API v2 샘플 저장소를 클론하거나 다운로드합니다.

활동의 자바 버전을 확인하세요.

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.mapwithmarker;

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;

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback 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 receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions()
            .position(sydney)
            .title("Marker in Sydney"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

    

활동의 Kotlin 버전을 확인하세요.

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.mapwithmarker

import android.os.Bundle
import android.widget.Toast
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

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
      val sydney = LatLng(-33.852, 151.211)
      googleMap.addMarker(
        MarkerOptions()
          .position(sydney)
          .title("Marker in Sydney")
      )
      googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

    

개발 프로젝트 설정

다음 단계에 따라 Android 스튜디오에서 튜토리얼 프로젝트를 만듭니다.

  1. Android 스튜디오를 다운로드하여 설치합니다.
  2. Android 스튜디오에 Google Play 서비스 패키지를 추가합니다.
  3. 이 튜토리얼을 읽기 전에 미리 하지 않은 경우, Google Maps Android API v2 샘플 저장소를 클론하거나 다운로드합니다.
  4. 튜토리얼 프로젝트를 가져옵니다.

    • Android 스튜디오에서 File > New > Import Project를 선택합니다.
    • Google Maps Android API v2 샘플 저장소를 다운로드한 후 저장한 위치로 이동합니다.
    • 다음 위치에서 MapWithMarker 프로젝트를 찾습니다.
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker(자바) 또는
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker(Kotlin)
    • 프로젝트 디렉터리를 선택한 다음 Open을 클릭합니다. 이제 Android 스튜디오에서 Gradle 빌드 도구를 사용하여 프로젝트를 빌드합니다.

필요한 API 사용 설정 및 API 키 가져오기

이 튜토리얼을 완료하려면 필요한 API가 사용 설정되고 Android용 Maps SDK를 사용할 수 있도록 승인된 API 키가 포함된 Google Cloud 프로젝트가 필요합니다. 자세한 내용은 다음을 참고하세요.

앱에 API 키 추가

  1. 프로젝트의 local.properties 파일을 엽니다.
  2. 다음 문자열을 추가한 다음 YOUR_API_KEY를 API 키 값으로 대체합니다.

    MAPS_API_KEY=YOUR_API_KEY
    

    앱을 빌드할 때 아래 설명된 대로 Android용 Secrets Gradle Plugin에서 API 키를 복사하여 이를 Android 매니페스트에서 빌드 변수로 제공합니다.

앱 빌드 및 실행

앱을 빌드 및 실행하려면 다음 안내를 따르세요.

  1. 컴퓨터에 Android 기기를 연결합니다. 안내에 따라 Android 기기에서 개발자 옵션을 사용 설정하고 기기를 감지하도록 시스템을 구성합니다.

    또는 Android Virtual Device(AVD) Manager를 사용하여 가상 기기를 구성할 수 있습니다. 에뮬레이터를 선택할 때 Google API가 포함된 이미지를 선택해야 합니다. 자세한 내용은 Android 스튜디오 프로젝트 설정을 참고하세요.

  2. Android 스튜디오에서 Run 메뉴 옵션(또는 재생 버튼 아이콘)을 클릭합니다. 표시되는 메시지에 따라 기기를 선택합니다.

Android 스튜디오에서 Gradle을 호출하여 앱을 빌드한 다음 기기 또는 에뮬레이터에서 앱을 실행합니다. 이 페이지의 이미지와 비슷하게, 오스트레일리아의 동쪽 해안에 있는 시드니를 가리키는 마커가 있는 지도가 표시됩니다.

문제 해결:

코드 이해하기

여기에서는 유사한 앱을 빌드하는 방법을 이해할 수 있도록 MapWithMarker 앱의 가장 중요한 부분을 설명합니다.

Android 매니페스트 확인

앱의 AndroidManifest.xml 파일에서 다음 요소를 확인합니다.

  • meta-data 요소를 추가하여 앱이 컴파일된 Google Play 서비스의 버전을 삽입합니다.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • API 키를 지정하는 meta-data 요소를 추가합니다. 이 튜토리얼에 포함된 샘플에서는 API 키의 값을 앞부분에서 정의한 키의 이름(MAPS_API_KEY)과 일치하는 빌드 변수에 매핑합니다. 앱을 빌드할 때 Android용 Secrets Gradle Plugin에서 local.properties 파일의 키를 매니페스트 빌드 변수로 제공합니다.

    <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="${MAPS_API_KEY}" />
    

    build.gradle 파일에서 다음 행이 API 키를 Android 매니페스트에 전달합니다.

      id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    

다음은 전체 매니페스트의 예입니다.

<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2020 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="${MAPS_API_KEY}" />

        <activity
            android:name=".MapsMarkerActivity"
            android:label="@string/title_activity_maps"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

지도 추가

Android용 Maps SDK를 사용하여 지도를 표시합니다.

  1. 활동의 레이아웃 파일인 activity_maps.xml<fragment> 요소를 추가합니다. 이 요소는 지도의 컨테이너 역할을 하고 GoogleMap 객체에 대한 액세스 권한을 제공하도록 SupportMapFragment를 정의합니다. 이 튜토리얼에서는 이전 버전 Android 프레임워크와의 호환성을 위해 지도 프래그먼트의 Android 지원 라이브러리 버전을 사용합니다.

    <!--
     Copyright 2020 Google LLC
    
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    -->
    
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
    
    
  2. 활동의 onCreate() 메서드에서 레이아웃 파일을 콘텐츠 뷰로 설정합니다. FragmentManager.findFragmentById()를 호출하여 지도 프래그먼트의 핸들을 가져옵니다. 그런 다음 getMapAsync()를 사용하여 지도 콜백에 등록합니다.

    자바

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    

    Kotlin

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }
    
  3. OnMapReadyCallback 인터페이스를 구현하고, GoogleMap 객체를 사용할 수 있을 때 지도를 설정하도록 onMapReady() 메서드를 재정의합니다.

    자바

    public class MapsMarkerActivity extends AppCompatActivity
            implements OnMapReadyCallback {
    
        // ...
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng sydney = new LatLng(-33.852, 151.211);
            googleMap.addMarker(new MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney"));
        }
    }
    

    Kotlin

    class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {
    
        // ...
    
        override fun onMapReady(googleMap: GoogleMap) {
          val sydney = LatLng(-33.852, 151.211)
          googleMap.addMarker(
            MarkerOptions()
              .position(sydney)
              .title("Marker in Sydney")
          )
        }
    }
    

기본적으로 Android용 Maps SDK는 사용자가 마커를 탭할 때 정보 창의 콘텐츠를 표시합니다. 기본 동작으로 충분하면 마커에 클릭 리스너를 추가하지 않아도 됩니다.

다음 단계

지도 객체마커로 할 수 있는 작업에 대해 자세히 알아보세요.