스타일 지도 추가

이 튜토리얼에서는 Android 앱에 맞춤 스타일이 지정된 지도를 추가하는 방법을 보여줍니다. 이때 커스텀 스타일의 예시로 야간 모드를 사용합니다.

스타일 옵션으로 표준 Google 지도 스타일의 표현을 맞춤설정하고 도로, 공원, 비즈니스, 기타 관심 장소 등과 같은 지형지물의 시각적 표시를 변경할 수 있습니다. 즉, 지도의 특정 구성요소를 강조하거나 지도에서 앱의 스타일을 보완할 수 있습니다.

스타일 지정은 normal 지도 유형에서만 가능합니다. 스타일을 지정해도 실내 지도에는 영향을 미치지 않습니다.

코드 가져오기

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

개발 프로젝트 설정

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

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

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

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

이 튜토리얼을 완료하려면 Android용 Maps SDK를 사용할 수 있도록 승인된 Google API 키가 필요합니다.

다음 버튼을 클릭하여 키를 가져오고 API를 활성화합니다.

키 가져오기

자세한 내용은 API 키 가져오기 가이드를 참고하세요.

앱에 API 키 추가

  1. 프로젝트의 gradle.properties 파일을 수정합니다.
  2. API 키를 GOOGLE_MAPS_API_KEY 속성의 값에 붙여넣습니다. 앱을 빌드할 때 Gradle에서 API 키를 앱의 Android 매니페스트에 복사합니다.

    GOOGLE_MAPS_API_KEY=PASTE-YOUR-API-KEY-HERE
    

앱 빌드 및 실행

  1. 컴퓨터에 Android 기기를 연결합니다. 안내에 따라 Android 기기에서 개발자 옵션을 사용 설정하고 기기를 감지하도록 시스템을 구성합니다. (또는 Android Virtual DeviceAndroid(AVD) Manager를 사용하여 가상 기기를 구성할 수 있습니다. 에뮬레이터를 선택할 때 Google API가 포함된 이미지를 선택해야 합니다. 자세한 내용은 시작 가이드를 참고하세요.)
  2. Android 스튜디오에서 Run 메뉴 옵션(또는 재생 버튼 아이콘)을 클릭합니다. 표시되는 메시지에 따라 기기를 선택합니다.

Android 스튜디오에서 Gradle을 호출하여 앱을 빌드한 다음 기기 또는 에뮬레이터에서 앱을 실행합니다. 이 페이지의 이미지와 비슷하게 어두운(야간 모드) 스타일의 지도가 표시됩니다.

문제 해결:

코드 이해하기

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

JSON 스타일 객체가 포함된 리소스 추가

JSON 형식의 스타일 선언이 포함된 리소스를 개발 프로젝트에 추가합니다. 다음 예시와 같이 원시 리소스 또는 문자열을 사용할 수 있습니다.

원시 리소스

야간 모드 스타일 지정을 위한 다음과 같은 JSON 스타일 선언을 포함하여 /res/raw/style_json.json에 원시 리소스를 정의합니다.

문자열 리소스

야간 모드 스타일 지정을 위한 다음과 같은 JSON 스타일 선언을 포함하여 /res/values/style_strings.xml에 문자열 리소스를 정의합니다. 이 튜토리얼에서는 문자열 이름 style_json을 사용합니다. 이 파일에서는 백슬래시를 사용하여 따옴표를 이스케이프 처리해야 합니다.

지도에 JSON 스타일 객체 전달

지도의 스타일을 지정하려면 JSON 형식의 스타일 선언이 포함된 MapStyleOptions 객체를 전달하는 GoogleMap.setMapStyle()을 호출하세요.

원시 리소스

다음 코드 샘플에서는 프로젝트에 style_json이라는 원시 리소스가 포함되어 있다고 가정합니다.

// 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.styledmap;

import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
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.MapStyleOptions;

/**
 * A styled map using JSON styles from a raw resource.
 */
public class MapsActivityRaw extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityRaw.class.getSimpleName();

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

        // Get the SupportMapFragment and register for the callback
        // when the map is ready for use.
        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 for use.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.style_json));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        // Position the map's camera near Sydney, Australia.
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(-34, 151)));
    }
}

레이아웃(activity_maps_raw.xml)은 다음과 같습니다.

문자열 리소스

다음 코드 샘플에서는 프로젝트에 style_json이라는 문자열 리소스가 포함되어 있다고 가정합니다.

package com.example.styledmap;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

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.MapStyleOptions;

/**
 * A styled map using JSON styles from a string resource.
 */
public class MapsActivityString extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityString.class.getSimpleName();

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

        // Get the SupportMapFragment and register for the callback
        // when the map is ready for use.
        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 for use.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {

        // Customise the styling of the base map using a JSON object defined
        // in a string resource file. First create a MapStyleOptions object
        // from the JSON styles string, then pass this to the setMapStyle
        // method of the GoogleMap object.
        boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
                .getString(R.string.style_json)));

        if (!success) {
            Log.e(TAG, "Style parsing failed.");
        }
        // Position the map's camera near Sydney, Australia.
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(-34, 151)));
    }
}

레이아웃(activity_maps_string.xml)은 다음과 같습니다.

JSON 스타일 선언 자세히 알아보기

스타일 지도에서는 두 가지 개념을 사용하여 지도에 색상과 기타 스타일 변경사항을 적용합니다.

  • 선택기는 지도에서 스타일을 지정할 수 있는 지리적 구성요소를 지정합니다. 여기에는 도로, 공원, 호수/바다 등과 해당 라벨이 포함됩니다. 선택기에는 featureTypeelementType 속성으로 지정된 지형지물요소가 포함됩니다.
  • 스타일러는 지도 요소에 적용할 수 있는 색상 및 표시 여부 속성으로 색조, 색상, 밝기/감마 값을 조합하여 표시되는 색상을 정의합니다.

JSON 스타일 지정 옵션에 관한 자세한 설명은 스타일 참조에서 확인하세요.

지도 플랫폼 스타일 지정 마법사

지도 플랫폼 스타일 지정 마법사를 사용하면 신속하게 JSON 스타일 지정 객체를 생성할 수 있습니다. Android용 Maps SDK는 Maps JavaScript API와 동일한 스타일 선언을 지원합니다.

다음 단계

스타일을 지정하여 지도에서 지형지물을 숨기는 방법을 알아보세요.