Develop/Flutter

[Flutter] 플러터 Google Map에서 현재 위치 좌표(위도, 경도) 찾기

JunJangE 2022. 1. 13. 10:33

이번에는 Google Map에서 현재 위치 좌표(위도, 경도)를 찾아보자.

Google Map API에서 GoogleMap 위젯을 살펴보면 다음과 함수가 있는 것을 확인할 수 있다.

  • initialCameraPosition : 초기 시작 시 지도 보기를 로드하는 데 사용되는 필수 매개변수
  • myLocationEnabled : 지도에 파란색 점으로 현재 위치를 표시
  • myLocationButtonEnabled : 사용자 위치를 카메라 뷰의 중앙으로 가져오는 데 사용되는 버튼
  • mapType : 표시할 지도의 유형(일반, 위성, 하이브리드 및 지형)을 지정
  • zoomGesturesEnabled : 지도 보기가 확대/축소 제스처에 응답해야 하는지 여부
  • zoomControlsEnabled : 확대/축소 컨트롤을 표시할지 여부(Android 플랫폼에만 해당).
  • onMapCreated : 지도를 사용할 준비가 되었을 때 콜백합니다.
  • minMaxZoomPreference : zoom 최대/최소
  • onCameraIdle : 카메라 이동이 멈췄을 때

위에 함수 중에서 myLocationEnabled , myLocationButtonEnabled를 ture로 설정해도 구글 맵에서 현재 위치 좌표를 나타낼 수 있다.

 GoogleMap(
 		
      initialCameraPosition: _initialPosition,
      mapType: MapType.normal,
      myLocationEnabled: true,
      myLocationButtonEnabled: true,
      
      //

    );
  }
 
그러나 버튼이 우측 상단에 고정되어 움직일 수 없게되고 사실상 현재 좌표를 찾지는 못하게 된다.

패키지

다음 패키지를 통해 직접 좌표를 구해보자.
 
 

location | Flutter Package

A Flutter plugin to easily handle realtime location in iOS and Android. Provides settings for optimizing performance or battery.

pub.dev

위 링크에서 Installing에 들어가 다음 패키지를 복사하고 pubspec.yaml의 dependencies에 다음 코드를 작성한다.

dependencies:
  location: ^4.3.0

코드

 Future<Position> getCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    return position;
  }

위도 : position.latitude 

경도 : position.longitude

위 코드를 통해 현재 좌표를 구할 수 있다.

다음으로 FloatingActionButton을 통해 Google Map에서 현재 위치로 이동시켜 보자.

          FloatingActionButton(
            onPressed: () async {
              var gps = await getCurrentLocation();

              _controller.animateCamera(
                  CameraUpdate.newLatLng(LatLng(gps.latitude, gps.longitude)));
 
            },
            child: Icon(
              Icons.my_location,
              color: Colors.black,
            ),
            backgroundColor: Colors.white,
          ),

이때 Google Map 함수에 myLocationEnabled를 ture로 설정하자.

위 코드를 작성하여 실행시키면 자신의 위치에 파란 점이 찍히는 것을 확인할 수 있다.

참고

 

location | Flutter Package

A Flutter plugin to easily handle realtime location in iOS and Android. Provides settings for optimizing performance or battery.

pub.dev