개발일지

Android In A..Z - Google API (Google Map) 본문

Android (안드로이드)

Android In A..Z - Google API (Google Map)

강태종 2021. 8. 18. 15:26

Android Google Map을 활용하여 간단하게 즐겨찾기 기능을 구현했습니다.


1. Application 등록

아래 사이트에 들어가서 Application을 등록한다.

 

https://console.cloud.google.com/?hl=ko 

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com


2. Google Map API 등록

API 서비스 -> API 라이브러리로 가서 Maps SDK for Android를 등록한다.

=> API Key가 발급된다.


3. API KEY 등록

AndroidMenifest.xml에 application사이에 <meta-data>를 통해서 KEY를 등록한다.

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

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

    <application
        android:usesCleartextTraffic="true"
        android:name=".application.HiltApplication"
        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.GoogleAPI">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_geo_api_key" />

        <activity
            android:windowSoftInputMode="adjustResize"
            android:name=".activity.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>

4. Gradle 설정

    // Google Map
    implementation 'com.google.android.gms:play-services-maps:17.0.1'

5. Map 사용

FragmentContainerView를 통해 SupportMapFragment를 지정한다.

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

    <data>
        <variable
            name="onLocationAdd"
            type="android.view.View.OnClickListener" />
    </data>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/floating_action_button"
            android:onClick="@{onLocationAdd}"
            android:src="@drawable/ic_round_add_location_24"
            android:contentDescription="@string/location_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginBottom="20dp"
            app:layout_anchor="@id/map"
            app:layout_anchorGravity="bottom|end"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>

 

실제로 MapView에 접근할 때 Fragment의 getMapAsync를 통해 Map을 접근할 수 있다.

@AndroidEntryPoint
class MapFragment : BindingFragment<FragmentMapBinding>(R.layout.fragment_map) {
    private val viewModel by activityViewModels<MapViewModel>()
    private val map by lazy { childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment }

    private var selectedPosition: LatLng? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        onCreatePlaceList()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        super.onCreateView(inflater, container, savedInstanceState)
        onCreateMarkerClickListener()
        onCreateOnLocationAdd()
        onCreateMap()

        return binding.root
    }

    private fun onCreateMap() {
        map.getMapAsync {
            it.setOnCameraMoveListener {
                binding.floatingActionButton.hide()
            }
            it.setOnMapClickListener { position ->
                selectedPosition = position
                binding.floatingActionButton.show()
            }
        }
    }


    private fun onCreatePlaceList() {
        viewModel.places.observe(viewLifecycleOwner) { list ->
            viewModel.clear()
            list.forEach { place ->
                map.getMapAsync { map ->
                    map.addMarker(
                        MarkerOptions().apply {
                            title(place.name)
                            position(LatLng(place.latitude, place.longitude))
                        }
                    ).also { marker ->
                        marker?.let { marker ->
                            marker.tag = place
                            viewModel.add(marker)
                        }
                    }
                }
            }
        }
    }

    private fun onCreateMarkerClickListener() {
        map.getMapAsync {
            it.setOnInfoWindowClickListener { marker ->
                val tag = marker.tag
                if (tag is Place) {
                    findNavController().navigate(MapFragmentDirections.actionMapFragmentToInformationDialog(tag))
                }
            }
        }
    }

    private fun onCreateOnLocationAdd() {
        binding.setOnLocationAdd {
            findNavController().navigate(MapFragmentDirections.actionMapFragmentToLocationAddDialog(selectedPosition))
        }
    }
}

Git (예제코드)

https://github.com/KangTaeJong98/Example/tree/main/Android/GoogleAPI

 

GitHub - KangTaeJong98/Example: My Example Code

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

'Android (안드로이드)' 카테고리의 다른 글

Android in A..Z - Module 베포 (Jitpack)  (0) 2021.09.02
Android in A..Z - Intent  (0) 2021.08.30
Android in A..Z - WebView Bridge  (0) 2021.08.05
Android in A..Z - Flow  (0) 2021.08.05
Android in A..Z - Context  (0) 2021.08.05
Comments