Android Google Map API


안드로이드 앱에서 Google Maps API를 사용하는 방법을 상세히 설명하고 예제를 제공합니다. 이 가이드에서는 Google Maps API를 설정하고, 지도를 표시하고, 사용자 위치를 보여주는 기본적인 예제를 다룹니다.

1. Google Maps API 설정

Step 1: Google Cloud 프로젝트 생성

  1. Google Cloud Console에 접속하여 프로젝트를 생성합니다.
  2. API & Services > Library로 이동합니다.
  3. “Maps SDK for Android”를 검색하여 해당 API를 활성화합니다.
  4. API & Services > Credentials로 이동하여 API 키를 생성합니다.

Step 2: 프로젝트 설정

  1. build.gradle (프로젝트 수준) 파일에 Google 서비스 및 Maps SDK 종속성을 추가합니다. buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.google.gms:google-services:4.3.10' } }
  2. build.gradle (앱 수준) 파일에 종속성을 추가하고, Google 서비스 플러그인을 적용합니다. plugins { id 'com.android.application' id 'com.google.gms.google-services' } android { // ... } dependencies { implementation 'com.google.android.gms:play-services-maps:18.0.2' implementation 'com.google.android.gms:play-services-location:21.0.1' }

2. Google Maps API 사용 예제

Step 1: AndroidManifest.xml 설정

Google Maps API 키를 AndroidManifest.xml 파일에 추가합니다.

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApp">
        <!-- 추가된 항목 시작 -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY"/>
        <!-- 추가된 항목 끝 -->
        <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>

Step 2: 레이아웃 파일에 MapFragment 추가

res/layout/activity_main.xml 파일에 MapFragment를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

Step 3: MainActivity.java 파일 설정

Google Maps API를 사용하여 지도를 초기화하고, 현재 위치를 표시하는 코드를 작성합니다.

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
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.google.android.gms.tasks.OnSuccessListener;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1;
    private GoogleMap mMap;
    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // SupportMapFragment를 얻고 지도가 사용 준비가 되었을 때 알림을 받는다.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // 마커를 추가하고 카메라를 이동시킨다.
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        // 현재 위치를 보여준다.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
            return;
        }
        mMap.setMyLocationEnabled(true);

        // 현재 위치로 카메라를 이동시킨다.
        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
                        }
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 다시 권한을 확인하고 위치 설정을 활성화한다.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);

                    fusedLocationClient.getLastLocation()
                            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                                @Override
                                public void onSuccess(Location location) {
                                    if (location != null) {
                                        LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
                                    }
                                }
                            });
                }
            }
        }
    }
}

3. 요약

위의 단계를 통해 안드로이드 앱에서 Google Maps API를 사용하여 지도를 표시하고, 사용자의 현재 위치를 얻고, 이를 지도에 표시하는 방법을 배웠습니다. Google Maps API는 매우 강력한 도구이며, 이를 활용하여 다양한 지도 기반 기능을 구현할 수 있습니다. 이 예제를 확장하여 지도 상에 마커를 추가하거나, 경로를 표시하는 등 다양한 기능을 구현할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *