Android Studio/기능 사용법

Android Studio : (1) Google map 불러오기 설정 방법 (API 키설정 필요 매우 복잡)

신강희 2024. 6. 19. 12:03
728x90

< (1) Google map 불러오기 설정 방법 (API 키설정 필요 매우 복잡) >

 

# 안드로이드 스튜디오에서 구글맵을 불러와서 사용하는 방법

- 과정이 매우복잡하다 가이드를 그대로 따라해서 실행 (순서가 바뀔경우 설치가 실패하거나 에러 발생)

- 참고 : https://developers.google.com/maps/documentation/android-sdk/config?hl=ko

 

Set up an Android Studio project  |  Maps SDK for Android  |  Google for Developers

New map styling is coming soon to Google Maps Platform. This update to map styling includes a new default color palette and improvements to map experiences and usability. All map styles will be automatically updated in March 2025. For more information on a

developers.google.com

 

# 로직이 아니라 매뉴얼대로 그대로 작성하여 사용하는것이므로 필요하면 복사붙여넣기로 사용!

1) 안드로이드 스튜디오 환경 확인 필요!

- 프로젝트 생성후 Graadle Scripts > settings.gradel.kts 에서 해당 설정 항목 있는지 확인

 

- 보통 자동 생성되나 없을시엔 하단 항목은 꼭 추가 되어야함

// 없을시에만 추가!!
// 혹시 추가했다면 우측 상단에 Sync now 눌러줘야함!

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

 

- 전체 작성 화면 위치 중요하니 참고!

pluginManagement {
    repositories {
        google {
            content {
                includeGroupByRegex("com\\.android.*")
                includeGroupByRegex("com\\.google.*")
                includeGroupByRegex("androidx.*")
            }
        }
        mavenCentral()
        gradlePluginPortal()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "Map"
include(":app")

 

2) build.gradle.kts (Module :app) 파일에 라이브러리 설치 및 구문 추가 필요

 

- 최상단 plugins{} 안에 ID 추가!

id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")

 

- android {} 안에 compileSdk 버전과 minSkd 버전 최소 충족요건 확인! (최소 버전보다 높으면 수정 X)

android {
    compileSdk = 34

    defaultConfig {
        minSdk = 19
        // ...
    }
}

 

- 그리고 동일한 android{} 안에 buileFeatures 구문 없다면 추가

buildFeatures {
buildConfig = true
}

 

- 그리고 맨마지막 dependencies{} 안에 라이브러리 추가!

- 해당 구문까지 작성했으면 우측 상단에 Sync Now 눌러서 설치!

// 구문 작성하고 꼭 우측 상단에 Sync now 눌러줘야함!!

implementation("com.google.android.gms:play-services-maps:18.2.0")

 

build.gradle.kts (Module :app) 파일 전체 코드 구문 위치 중요하니 참고!!

plugins {
    alias(libs.plugins.androidApplication)
}

secrets {
    // Optionally specify a different file name containing your secrets.
    // The plugin defaults to "local.properties"
    propertiesFileName = "secrets.properties"

    // A properties file containing default secret values. This file can be
    // checked in version control.
    defaultPropertiesFileName = "local.defaults.properties"

    // Configure which keys should be ignored by the plugin by providing regular expressions.
    // "sdk.dir" is ignored by default.
    ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
    ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
}

android {
    namespace = "com.ksg.map"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.ksg.map"
        minSdk = 21
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    buildFeatures {
        buildConfig = true

    }
}

dependencies {

    implementation(libs.appcompat)
    implementation(libs.material)
    implementation(libs.activity)
    implementation(libs.constraintlayout)
    testImplementation(libs.junit)
    androidTestImplementation(libs.ext.junit)
    androidTestImplementation(libs.espresso.core)

    implementation("com.google.android.gms:play-services-maps:18.2.0")

}

 

3) build.gradle.kts (Project: 프로젝트명) 파일에 구문 작성 필요!

 

- 하단에 buildscript 구문 추가 (구문 작성하고 Sync Now 눌러서 설치!)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    alias(libs.plugins.androidApplication) apply false
}

buildscript {
    dependencies {
        classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1")
    }
}

 

- 설치가 완료되면, 바로 이전에 작성했었던 build.gradle 모듈 파일에 최상단에 플러그인안에 id 추가!

- 추가 하고 나서 Sync Now 눌러서 설치! (순서가 바뀌거나 설치를 안하고 넘어가면 에러 발생됨)

id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")

 

4) secrets.properties 파일을 생성해서 API KEY 값을 넣어줘야함!

- 안드로이드 스튜디오에서 좌측 상단 모드를 프로젝트 파일로 변경

 

- 파일 생성해서 명칭을 secrets.properties 로 생성

 

- 이파일안에 API키를 생성해서 넣어줘야함

MAPS_API_KEY=AIzaSyBOvVFOxA9EPIHnLuq3jZLO3UgxFIV가나다라마바사

 

- API는 구글 클라우드 접속해서 하단 과정대로 진행!

- Maps SDK for Android 라이브러리 검색

 

- 사용하기 선택

 

- 키를 새로 생성하였도 되고, 기존에 있던 키에 권한만 추가하여도 됨

 

- 키값 넣기 완료

 

5) 방금 위에 방법과 동일하게 파일을 하나더 생성!

- local.defaults.properties 라는 명칭으로 생성

- 그 파일안에 해당 구문 작성! 여기에는 API 키는 안넣어줘도됨.

MAPS_API_KEY=DEFAULT_API_KEY

 

6) 이렇게 API 저장 완료 후에 AndroidManifest.xml 파일 안에 구문 추가!

- application{} 안에 작성 (위치 중요!)

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

 

7) 이제 다시 build.gradle 모듈 파일 안에 plugins 하단에 해단 구문 그대로 작성! (위치 중요!)

- 작성 완료 후에 꼭 Sync now로 설치해줄것!

secrets {
    // Optionally specify a different file name containing your secrets.
    // The plugin defaults to "local.properties"
    propertiesFileName = "secrets.properties"

    // A properties file containing default secret values. This file can be
    // checked in version control.
    defaultPropertiesFileName = "local.defaults.properties"

    // Configure which keys should be ignored by the plugin by providing regular expressions.
    // "sdk.dir" is ignored by default.
    ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
    ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
}

 

8) 설치가 완료 된뒤에 다시 AndroidManifest.xml에 추가 구문 작성

- 우선 유저 권한 추가 세가지

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

- 그리고 이전에 작성했던 application{} 안에 meta-data 밑에 이어서 작성

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

 

- 최종 AndroidManifest.xml 작성 파일 (위치가 중요하니 작성할때 참고!)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Map"
        tools:targetApi="31">

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

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


        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

 

# 이렇게 완료하면 기본 설정은 끝!

- 매우 복잡하나 참고한 링크나 해당글 순서대로 진행하면 되고, 순서가 틀릴경우 인식이 되지 않아 오류가 발생될수 있다고 하니 순서에 맞춰서 실행하는게 좋음!

 

다음 게시글로 계속~!

 

반응형