[Flutter] google map API 사용하기 + 현재 위치의 지도 불러오기

Gyuhan Park·2023년 11월 23일
0

react-native

목록 보기
7/7

💭 TMI

모바일 앱개발이라는 강의를 들으면서 flutter로 모바일 애플리케이션을 개발하고 있다. 웹 프론트엔드 개발자를 진로로 생각하고 있는데 같은 클라이언트단이기 때문에 흥미롭게 사용하고 있다.

react-native로도 앱을 개발했었는데 flutter에서 제공해주는 widget이 많아서 생산성이 훨씬 높고 성능도 좋아보인다. 웹보다 앱이 메인이라면 flutter로 android, ios 모두 배포할 수 있게 사용할 것 같다.
아무튼 이번엔 flutter에서 구글 지도를 불러오는 방법을 알아보자.

[ 요약 ]
1. google map API KEY 발급받기
2. flutter 프로젝트 환경 설정하기
3. flutter pub add google_maps_flutter 로 패키지 설치
4. 패키지 import하고 GoogleMap() widget으로 지도 불러오기

🔑 API KEY 발급

일단 google map API key를 발급받아야 한다.
GCP 콘솔 에 접속하여 프로젝트를 생성하고 Google Maps Platform 을 검색한다.

처음 들어가면 키를 발급받을 수 있도록 자동으로 리다이렉트해주는데 안뜬다면 왼쪽 사이드바의 키 및 사용자 인증 정보 를 클릭하여 API 키를 발급받는다.

이때 하나의 애플리케이션에서만 사용할 수 있도록 제한할 수 있는데 안내에 따라 SHA-1 인증서를 발급받고 Android 제한사항 에 추가한다.

# MAC 명령어
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

패키지명은 flutter 프로젝트 디렉토리 > android > app > build.gradle 에서 찾을 수 있다.

android {
	...
	namespace "패키지명"
    ...
}

⚙️ flutter 프로젝트 환경설정

키를 발급받았다면 flutter 프로젝트에 적용해보자. 환경설정할 때 이상한 오류들이 많이나게 되는데 버전이 안맞거나 xml 파일이 잘못되어 권한이 없는 것이므로 잘 확인하여 작성하자.

일단 google 지도를 가져올 수 있는 패키지를 설치한다.

flutter pub add google_map_flutter

그리고 android > app > src > main > AndroidManifest.xml 파일을 수정한다.
uses-permission : 사용자의 위치권한을 받아올 수 있다.
meta-data : 발급받은 지도 API KEY를 넣는다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="패키지명">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application
		...
        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="API KEY 값"/>
        <activity>
        	...
        </activity>
        ...
    </application>
</manifest>

🫥 API KEY 환경변수 숨기기

근데 설정에서 키 사용을 제한해뒀지만 API KEY가 코드에 노출된 게 찝찝하고 마음에 들지 않는다.

local.properties, app/build.gradle, app/src/main/AndroidManifest.xml 총 3개의 파일을 수정해야한다.

local.properties
키값을 불러올 이름과 함께 넣어준다.
처음 프로젝트 생성할 때 되어있겠지만 .gitignore 에 포함되어 있는 지 확인한다.

flutter.GoogleMapKey=키값

app/build.gradle
기존의 작성된 코드와 유사하게 local.properties의 값을 가져온다.

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')

def flutterGoogleMapKey = localProperties.getProperty('flutter.GoogleMapKey')
if (flutterGoogleMapKey == null) {
    flutterGoogleMapKey = ''
}

android {
	defaultConfig {
		...
        resValue "string", "GOOGLE_MAP_KEY", flutterGoogleMapKey
    }
}

app/src/main/AndroidManifest.xml
앞에서 키값을 직접 넣어줬던 부분을 다음과 같이 시크릿키로 설정할 수 있다.

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

🗺️ 화면에 지도 불러오기

설정을 완료했다면 google map을 사용할 수 있다.

먼저 파일에서 패키지를 import 한다.

import 'package:google_maps_flutter/google_maps_flutter.dart';

GoogleMap이라는 위젯을 자신의 프로젝트에 맞게 적용시킨다.

Container(
	child: GoogleMap(
		mapType: MapType.normal,
		initialCameraPosition: const CameraPosition(
		target: LatLng(37.50508097213444, 126.95493073306663),
		zoom: 18
	)
),

🧭 현재 위치로 이동하기

초기 좌표값을 넣어 지도를 띄웠다면 현재 위치 주변 지도를 띄우고 싶을 것이다. 버튼을 클릭하면 현재 위치로 지도가 이동하도록 해보자.

먼저 현재 위치를 가져올 수 있는 패키지를 설치한다.

flutter pub add location

그리고 기존의 코드에 설치한 패키지를 import한다.

import 'package:location/location.dart';

버튼 이벤트로 넣을 함수를 새로 만든다.
Location 객체를 불러와 location.getLocation() 비동기 함수를 통해 현재 위치를 가져온다.

  void _currentLocation() async {
    final GoogleMapController controller = await _controller.future;
    Location location = Location();
    final currentLocation = await location.getLocation();


    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        target: LatLng(currentLocation.latitude!, currentLocation.longitude!),
        zoom: 18.0,
      ),
    ));
  }

⚙️ 에뮬레이터 위치 설정하기

근데 제대로 실행이 됐으면 이상한 위치로 지도가 이동할 것이다!!!
그 이유는 에뮬레이터가 gps 기능이 없기 때문인데 안드로이드 스튜디오에서 에뮬레이터의 오른쪽 상단의 설정을 클릭하면 location을 설정할 수 있다.
위도, 경도를 추가하면 에뮬레이터에서의 현재위치를 지정할 수 있다.

profile
단단한 프론트엔드 개발자가 되고 싶은

0개의 댓글