[flutter] 플러터에서 지도 위에 현재 위치 표시하기
현재 위치 엑세스 권한 획득
우선, 현재 위치를 표시하려면 위치 엑세스 권한을 얻어야 합니다. geolocator
패키지를 사용하여 이를 구현할 수 있습니다. 아래는 pubspec.yaml
파일에 패키지를 추가하는 방법입니다.
dependencies:
geolocator: ^7.0.3
위의 명령어를 실행하여 패키지를 내려받습니다.
지도에 현재 위치 표시하기
다음으로, 지도에 현재 위치를 표시하는 방법을 알아봅시다. 이를 위해서는 google_maps_flutter
패키지를 사용할 수 있습니다. 아래는 지도 위에 현재 위치를 표시하는 예제 코드입니다.
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class MapWithCurrentLocation extends StatefulWidget {
@override
_MapWithCurrentLocationState createState() => _MapWithCurrentLocationState();
}
class _MapWithCurrentLocationState extends State<MapWithCurrentLocation> {
GoogleMapController mapController;
LatLng _currentPosition;
@override
void initState() {
super.initState();
_getCurrentLocation();
}
void _getCurrentLocation() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
setState(() {
_currentPosition = LatLng(position.latitude, position.longitude);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GoogleMap(
onMapCreated: (GoogleMapController controller) {
mapController = controller;
},
initialCameraPosition: CameraPosition(
target: _currentPosition,
zoom: 15.0,
),
markers: _currentPosition == null
? {}
: {
Marker(
markerId: MarkerId("currentPosition"),
position: _currentPosition,
infoWindow: InfoWindow(title: "Current Position"),
),
},
),
);
}
}
위의 코드에서는 geolocator
패키지를 사용하여 현재 위치를 가져오고, google_maps_flutter
패키지를 사용하여 지도에 현재 위치를 표시합니다.
이제 위의 예제코드를 사용하여 플러터 애플리케이션에서 지도에 현재 위치를 표시할 수 있습니다.
참고자료: