[ Flutter ] Google Map 현재 위치로 이동하는 버튼 만들기
어제보다 나은 사람이 되기

걱정보단 실행을, 그러나 계획적으로

Box World 자세히보기

개발/Flutter

[ Flutter ] Google Map 현재 위치로 이동하는 버튼 만들기

Box형 2021. 2. 26. 03:23
반응형

 이번 포스팅에서는 Flutter에서 Google map을 사용할 때 현재 자신의 위치로 camera position을 이동시키는 버튼을 구현해보겠습니다.

 사실 다음과 같이 myLocationButtonEnabled: true로 주셔도 버튼이 생성되는데, 이 경우에 버튼이 오른쪽 상단에 생기는데 위치를 변경하지 못하는 문제점이 발생합니다. 

GoogleMap(
            mapType: _googleMapType,
            initialCameraPosition: _initialCameraPostion,
            onMapCreated: (GoogleMapController controller) async {
             //
            },
            myLocationEnabled: true,
            #################################################
            myLocationButtonEnabled: true,
            #################################################
            zoomControlsEnabled: false,
            markers: _markers,

          ),

 그래서 직접 구현해보고자 합니다!

 

 

 

 

 


 우선 location package를 설치해주세요.

pub.dev/packages/location

 

location | Flutter Package

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

pub.dev

 그 후 다음과 같이 눌렀을 때 현재 위치로 이동할 버튼onTap 이벤트 발생 시 현재 위치로 이동하게 해주는 _currentLocation함수를 정의한 후 코드에 적용해주시면 끝입니다!

GestureDetector(
            onTap: (){
              _currentLocation();
            },
            child: Container(
              width: screenWidth*(40/360),
              height: screenWidth*(40/360),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.0),
                color: Colors.white,
              ),
              child: Padding(
                padding:  EdgeInsets.all(screenWidth*(6/360)),
                child: SvgPicture.asset(
                  GreyMyLocationIcon,
                  width: screenWidth*(28/360),
                  height: screenWidth*(28/360),
                ),
              ),
            ),
          ),
          
          
void _currentLocation() async {
    final GoogleMapController controller = await _controller.future;
    LocationData currentLocation;
    var location = new Location();
    try {
      currentLocation = await location.getLocation();
    } on Exception {
      currentLocation = null;
    }

    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 14.0,
      ),
    ));
  }
반응형