목차
소개
Flutter는 크로스 플랫폼 앱 개발 프레임워크로, 단일 코드베이스로 iOS와 Android에서 동작하는 애플리케이션을 만들 수 있습니다. 이번 튜토리얼에서는 Flutter의 Geolocator 라이브러리와 네이버맵 API를 활용하여 위치 기반 검색 애플리케이션을 개발하는 방법을 알아보겠습니다.
Geolocator 라이브러리 설치
Geolocator는 Flutter에서 위치 정보를 가져오는 데 사용되는 라이브러리입니다. pubspec.yaml
파일에 아래의 의존성을 추가하여 Geolocator 라이브러리를 설치할 수 있습니다.
dependencies:
geolocator: ^7.0.1
설치가 완료되면 flutter pub get
명령어를 실행하여 패키지를 가져옵니다.
네이버맵 API 키 발급
네이버맵 API는 네이버에서 제공하는 지도 서비스를 이용하기 위해 발급해야 합니다. 네이버 클라우드 플랫폼(https://www.ncloud.com/)에 접속하여 가입한 후, 네이버맵 API 키를 발급받아야 합니다.
위치 권한 설정
위치 기반 서비스를 사용하기 위해서는 앱에서 위치 권한을 요청해야 합니다. AndroidManifest.xml 파일에서 위치 권한을 추가합니다.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
...
</manifest>
iOS에서는 Info.plist 파일에 다음 항목을 추가합니다.
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location permission is required to show your current location on the map.</string>
위치 정보 가져오기
Geolocator 라이브러리를 사용하여 현재 위치 정보를 가져오는 함수를 작성해보겠습니다.
import 'package:geolocator/geolocator.dart';
Future<Position> getCurrentLocation() async {
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission != LocationPermission.whileInUse &&
permission != LocationPermission.always) {
// 위치 권한을 허용하지 않은 경우 처리
return null;
}
}
return await Geolocator.getCurrentPosition();
}
위 함수를 호출하여 현재 위치 정보를 가져올 수 있습니다.
Position position = await getCurrentLocation();
if (position != null) {
double latitude = position.latitude;
double longitude = position.longitude;
// 위치 정보 사용
} else {
// 위치 정보가 없는 경우 처리
}
네이버맵을 통한 위치 검색
네이버맵 API를 사용하여 지정된 위치 주변의 장소를 검색할 수 있습니다. 네이버맵 API 키를 발급받은 후, 아래와 같이 API 호출을 위한 함수를 작성합니다.
import 'package:http/http.dart' as http;
Future<List<Place>> searchPlaces(double latitude, double longitude) async {
String apiKey = "YOUR_NAVER_MAP_API_KEY";
String urlString =
"https://naveropenapi.apigw.ntruss.com/map-place/v1/search?query=&coordinate=$longitude,$latitude";
var response = await http.get(Uri.parse(urlString), headers: {
"X-NCP-APIGW-API-KEY-ID": apiKey,
"X-NCP-APIGW-API-KEY": apiKey,
});
if (response.statusCode == 200) {
var data = json.decode(response.body);
var places = data['places'] as List;
return places.map((place) => Place.fromJson(place)).toList();
} else {
throw Exception('Failed to load places');
}
}
위 함수를 호출하여 위치 주변의 장소를 검색할 수 있습니다.
List<Place> places = await searchPlaces(latitude, longitude);
if (places.isNotEmpty) {
// 검색된 장소 사용
} else {
// 검색된 장소 없음 처리
}
위의 예제 코드를 참고하여 Flutter에서 Geolocator와 네이버맵 API를 이용한 위치 기반 검색 애플리케이션을 개발할 수 있습니다.
참고자료: