살아있는감각

안드로이드 구글맵 API 사용 예제

fusionism 2020. 5. 21. 18:50
반응형

첫번째 (안드로이드 스튜디오 설치)

 

두번째 (안드로이드 스튜디오에 Google Play Services 추가)

아래 화면의 Google Play가 들어간 항목을 다 선택했는데, 꼭 필요한지는 아시는분이 댓글 부탁......;;

File > Settting > Appearance&Behavior > AndroidSDK

 

업데이트 관련 참고 URL

https://developer.android.com/studio/intro/update.html#sdk-manager

 

IDE 및 SDK 도구 업데이트  |  Android 개발자  |  Android Developers

Android 스튜디오를 설치하면 자동 업데이트 및 Android SDK Manager를 사용하여 Android 스튜디오 IDE 및 Android SDK 도구를 쉽게 최신 버전으로 유지할 수 있습니다.

developer.android.com

세번째 (안드로이드 스튜디오 프로젝트 생성)

아래 화면과 같이 구글 맵 엑티비티 추가

구글맵 엑티비티 생성

생성 후, AndroidManifest.xml 추가 내용

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
.
.
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".maps.MapsGoogle1Activity"
            android:label="@string/title_activity_maps_google1"></activity>

res/values/google_map_api.xml 파일 내용

GoogleMaps API KEY가 필요하다는 내용과 생성 요청을 위한 2가지 방법의 URL이 보이고, 구글 API 등록 시 사용될 package name과 SHA1 Fingerprint를 확인 할 수 있음.

<resources>
<!--
TODO: Before you run your application, you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:

https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=11:11:11:11:FE:BC:33:8E:71:E4:A6:88:ED:AB:CC:E7:4C:D8:47:50%3Bcom.psw.example.maps

You can also add your credentials to an existing key, using these values:

Package name:
com.psw.example.maps

SHA-1 certificate fingerprint:
11:11:11:11:FE:BC:33:8E:71:E4:A6:88:ED:AB:CC:E7:4C:D8:47:50

Alternatively, follow the directions here:
https://developers.google.com/maps/documentation/android/start#get-key

Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
-->
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
</resources>

 

4번째  (구글 MAP API KEY 생성)

위 주석의 첫번째 URL 접속 (구글 클라우드) - 구글 클라우드 계정 필요

API 등록 

앱 사용량 제한 항목에 google_map_api.xml 에서 확인된 package name과 SHA1 fingerprint 값을 등록하고 APIKey 값은 아래 YOUR_KEY_HERE 부분에 업데이트

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>

라이브러리 항목에 아래 항목이 사용 설정 되었는지 확인 (안되어 있으면 사용 설정)

 

 

Activity 기본 생성 코드

package com.psw.example.maps;

import androidx.fragment.app.FragmentActivity;

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;
import com.psw.example.R;

public class MapsGoogle1Activity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps_google1);
        // 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));
    }
}

 

뭔가 잘못된 경우 아래와 같은 오류가 발생하는데, APIKEY 값과 관련 참고 값들을 확인하여 수정해 준다.

E/Google Maps Android API: Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
    	API Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    	Android Application (<cert_fingerprint>;<package_name>): xxxxxxxxxxxxxxxxxxxxxxxxxxxxx;com.psw.example

 

정상적으로 반영이 되었다면 앱 구동 시, 아래와 같은 화면을 볼 수 있다.

 

 

반응형