MapSample - Just Sample App using Naver Map API

Related tags

App MapSample
Overview

Sample Project: NaverMap 맛보기

Gradle Dependency

// App 단위 Gradle
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        // 이런 식으로 naver maven 설정
        maven { url 'https://naver.jfrog.io/artifactory/maven/' }
    }
}

// 모듈 단위 Gradle
dependencies {
    /* etc */

    // Naver Map Dependency
    implementation 'com.naver.maps:map-sdk:3.13.0'
    // 위치 추적 Dependency 
    implementation 'com.google.android.gms:play-services-location:19.0.0'
}

위와 같이 의존성 추가를 한다

Implementation

MapView와 NaverMap

NaverMap 공식문서를 참조해보면 MapView에 NaverMap 객체를 끼워넣어야 Map 기능이 정상적으로 작동할 수 있다는 것을 알 수 있다.
이번 Practice에서는 MapFragment를 사용하지 않았다 .(그런데 이번 프로젝트에서는 이걸 사용할 것 같진않다, 화면에 지도를 넣어야하는 것이어서)

Usage

Activity에 MapView를 선언한다

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context=".MainActivity">

    <!-- TextView 생략 -->

    <com.naver.maps.map.MapView android:id="@+id/map_main" android:layout_width="0dp"
        android:layout_height="360dp" android:layout_marginHorizontal="16dp"
        android:layout_marginTop="24dp" app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_title" />

</androidx.constraintlayout.widget.ConstraintLayout>

MapView를 Parent의 생명주기에 맞춘다

LifecycleCallback뿐만 아니라 onLowMemory, onSavedInstanceState 등도 같이 맞추라고 하는데 이걸 한 클래스에서 다 적으면 가독성에 지대한 영향을 줄 것이 뻔하니 DefaultLifecycleObserver를 활용하여 분리할 수 있는 코드는 분리한다.

// MainActivity.kt
override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    binding.mapMain.onSaveInstanceState(outState)
}

override fun onLowMemory() {
    super.onLowMemory()
    binding.mapMain.onLowMemory()
}

private class MapViewLifecycleObserver(
    private val mapView: MapView,
    private val savedInstanceState: Bundle?
) : DefaultLifecycleObserver {
    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        mapView.onCreate(savedInstanceState)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        mapView.onDestroy()
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        mapView.onPause()
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        mapView.onResume()
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        mapView.onStart()
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        mapView.onStop()
    }
}

// onCreate에서 LifecycleObserver 등록
lifecycle.addObserver(MapViewLifecycleObserver(binding.mapMain, savedInstanceState))

MapView에 NaverMap 객체를 끼워넣는다

코드를 깊이 살펴보진 못했으나, OnMapReadyCallback.onMapReady()에서 패러미터로 주어지는 NaverMap 객체를 MapView에 넣는 것으로 보인다. Activity에 OnMapReadyCallback를 구현하는 것이 역할에 안맞는 것 같아서 이 역시 NaverMapProvider라는 클래스로 분리하여 주입한다

private class NaverMapProvider(
    private val trackingLocationSource: LocationSource,
    private var activityNaverMap: NaverMap? = null
) : OnMapReadyCallback {
    override fun onMapReady(naverMap: NaverMap) {
        activityNaverMap = naverMap.apply {
            mapType = NaverMap.MapType.Navi
            setLayerGroupEnabled(NaverMap.LAYER_GROUP_TRANSIT, false)
            setLayerGroupEnabled(NaverMap.LAYER_GROUP_BUILDING, true)
            isNightModeEnabled = true
            locationSource = trackingLocationSource
            locationTrackingMode = LocationTrackingMode.Follow
            addOnLocationChangeListener { location ->
                cameraPosition =
                    CameraPosition(LatLng(location.latitude, location.longitude), 16.0)
            }
            uiSettings.run {
                isCompassEnabled = false
                isScaleBarEnabled = false
                isZoomControlEnabled = false
                isLocationButtonEnabled = true
            }
        }
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    // 여기에 NaverMapProvider 주입
    binding.mapMain.getMapAsync(NaverMapProvider(locationSource, naverMap))
}

위치추적 기능: LocationSource

우선 사용자의 위치를 받아오기 위해서는 위치정보 사용권한을 받아와야하는데, API 31부터 위치에 대한 정확한 정보를 안 넘겨줄 수도 있는 권한 항목이 신설, 강제화되어서 이때문에 꼴받고 싶지않다면 targetSdkVersion은 30으로 유지하는 것이 좋을 것 같다.

// 내부 코드 보면 생성자에서 권한 요청함
locationSource = FusedLocationSource(this, LOCATION_PERMISSION_REQUEST_CODE)

// 권한 요청의 결과 받아오기
override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    if (locationSource.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
        // 권한 승인이 나오면 위치추적하고 아니면 일반지도모드
        naverMap?.locationTrackingMode =
            if (!locationSource.isActivated) LocationTrackingMode.None
            else LocationTrackingMode.Follow
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

// NaverMap에서 실시간으로 위치를 받아와야하기에 NaverMap 객체에 locationSource 설정
activityNaverMap = naverMap.apply {
    /* etc */
    locationSource = trackingLocationSource
    /* etc */
}
Contributor

HyunWoo Lee

You might also like...
Simple Android app during a coding night. Just Learning Firebase and Android
Simple Android app during a coding night. Just Learning Firebase and Android

KUI-App Simple Android app during a coding night. Just Learning Firebase and Android What we learned: Some basics of Android Basic setup of Firebase:

This project is focused on the sample using the API's new preview version of Android-L, use of transitions, shadows etc...

Android L preview example Description This project is focused on the sample using the API's new preview version of Android-L, use of transitions, shad

A 2020s compatible React Native keyboard avoiding view for Android and iOS that just works.

react-native-keyboard-shift Example Snack coming soon Until then: Clone this repo: git clone https://github.com/FullStackCraft/react-native-keyboard-s

Find your new favorite wallpaper that looks just like you 🖌️
Find your new favorite wallpaper that looks just like you 🖌️

Wollpaper Find your new favorite wallpaper that looks just like you. Builds The pre-built app can be downloaded under "releases" on the right side of

Alfheim - Greetings to all players and those who just passed by in the Alfheim repository

Greetings to all players and those who just passed by in the Alfheim repository!

We will accompany you to the end of the heavens! Just tell us your destination in KemanaKita!.
We will accompany you to the end of the heavens! Just tell us your destination in KemanaKita!.

In this project we tried to make exploring and travelling the heavens in Indonesia much more fun and enjoyable. We aim to give you best tour guide in your phone!. We will develop this project in stages!

An Application to view recipes of different dishes. I just made it for training and sharpen my skills.
An Application to view recipes of different dishes. I just made it for training and sharpen my skills.

FoodRecipesApplication An Application to view recipes of different dishes. I just made it for training and sharpen my skills. I tried to write a clean

This is a Movie API app in which data is fetched online from the TMDB site using API authentication.

Movie-API This is a Movie API app in which data is fetched online from the TMDB site using API authentication. MVVM model is used for Database Managme

Gender Checker app built using Kotlin, MVVM, Genderize.io API. Take this as a reference for MVVM and Genderize.io API 🚀
Gender Checker app built using Kotlin, MVVM, Genderize.io API. Take this as a reference for MVVM and Genderize.io API 🚀

Gender-Checker 👀 Gender Checker app built using Kotlin, MVVM, Genderize.io API Enter a name and the app will guess the gender 🤩 ✨ Highligts: API : G

Owner
null
This Andoird project is about classifying garbage pictures using a CNN-based Tensorflowlite model and fetching location using GPS to mark its area on the map.

Grbage_Detector_And_Locator Description As per some of the recent reports published, in India, the pollution levels are increasing at a colossal pace

Sayantan Banerjee 5 Mar 5, 2022
Google map location tracker uploading current to realtime database and displaying location information from firebase realtime.

WEEK-8-SQ009-ANDROID LOCATION - GROUP WORK (2) Problem Description Track your partner(s). Implementation 1: You are to build a map application to show

null 0 Mar 16, 2022
TradeMap-Clone - Trade Map Clone with kotlin

TradeMap-Clone APP que simula atualização da bolsa de valores em tempo real para

Fernando Gomes 0 Feb 11, 2022
A mobile application that contains up-to-date information about the latest earthquakes in Turkey, scientific explanations about earthquakes, and Turkey's earthquake map.

Recent-Earthquakes A mobile application that contains up-to-date information about the latest earthquakes in Turkey, scientific explanations about ear

Nisa Efendioğlu 3 Dec 5, 2022
Just a simple tool to turn on/off DND(Do Not Disturb) automatically when using specified apps.

AutoDND Just a simple tool to turn on/off DND(Do Not Disturb) automatically when using specified apps. Ever feel disturbed by notifications and maybe

null 6 May 24, 2022
New-SplashScreen-API - SplashScreen API Implementation Sample

SplashScreen API Implementation Sample Installation - Usage <style name="Theme.A

Arda Kazancı 0 Jan 3, 2022
Water tracker app helps you with daily reminder to drink water. This app is just a trial to test and improve my android development skills.

?? About Me I am a self-thaught developer learning web and android development. This app is just a trial to test and improve my android development sk

Sinan Sonmez (Chaush) 28 Dec 17, 2022
Just a phone app.

Koler ** An update, im currently working on a massive code redesign from scratch, will probably take some time, but will be better A uniquely stylized

null 633 Jan 2, 2023
💰 Expense Manager is simple, intuitive, stable and modern app that is just designed for you.

Expense Manager is simple, intuitive, stable and modern app that is just designed for you. Everything you need at your fingertips to manage the expenditures and budgets.

Behzod Bozorboev 13 Oct 20, 2022
Just another Quotes app with beautiful UI which shows random quotes from the internet

RandomQuotes Just another Quotes app with beautiful UI which shows random quotes from the internet. Screenshots Libraries Volley Android Material API

Hamza Aziz 5 Mar 2, 2022