Flutter Google Map Geocoding and Geolocator

Flutter Google Map Geocoding and Geolocator

    Flutter Google Map LatLng, CameraPosition, Geocoding and Geolocator.

    We will learn step by step how to use Google Map, Geolocator and Geocoding get user's locatoin and  we will see how to get user's location dynamically as user tap on the map and save the user selected location. we will connect to back end. 

    We will cover the following topic

    1. Show Google Map

    2. Get address from lattiude and longittude

    3. Get locatoin based on user interaction 

    4. Save the location

    Create a project

    Let's go ahead and create a project for Google map. You can name it anything. Once the project has been created install these three packages

      google_maps_flutter: 
      geolocator: 
      geocoding: 

    Google Map

    To show google map we need to use GoogleMap() constructor in the UI code.

     GoogleMap(
                            initialCameraPosition: CameraPosition(target: _initialPosition,
                                zoom: 10),
                            onTap: (latLng) {
                              Get.toNamed(RouteHelper.getPickMapRoute('add-address', false),
                                  arguments: PickMapScreen(
                                fromAddAddress: true, fromSignUp: false,
                                    googleMapController: locationController.mapController,
                                route: null, canRoute: false,
                              ));
                            },
                            zoomControlsEnabled: false,
                            compassEnabled: false,
                            indoorViewEnabled: true,
                            mapToolbarEnabled: false,
                            onCameraIdle: () {
                              locationController.updatePosition(_cameraPosition, true);
                            },
                            onCameraMove: ((position) => _cameraPosition = position),
                            onMapCreated: (GoogleMapController controller) {
                              locationController.setMapController(controller);
                              locationController.getCurrentLocation(true, mapController: controller);
                            },
                          ),

    In the above code initialCameraPosition is very important. We must provide a default value using CameraPosition() class.

    onTap callback function takes latLng object. 

    There's onCameraIdle() which gets called when the camera is stopped. This method also gets called when the camera is done initializing first time.

    This method is a perfect place for updating different parameters related to google map.

    onMapCreated() is called once the map has been created, so it is also get called before onCameraIdle(). Here we may save the GoogleMapController instance locally in our app.

    As you move your camera(it means GoogleMap by dragging), onCameraMove callback gets called. It takes position coordinate. So here you can change your intial camera position _cameraPosition. As you move the map, you must change the _cameraPosition varaible using position.

    You also need to remmember, that onCameradle() gets called, after onCamera. It means, every time you drag, drop or change your map, onCameraIdle() gets called at the end.

    onCameraIdle callback is the best place to update your location controller. it also means updating the actual location or position.

    Address from LatLng

    Cameraposition iclass s the most important in terms of getting new location as user moves the map or drag the map. We can get exact address as string from google map server if we send the LatLng to it. 

    CameraPosition position (you can name it anything) object gives you access to target object.

    CameraPosition position;
    position.target.latitude;
    position.target.longitude;

    If you wrap the last two lines using LatLng(), then it will return and LatLng object.

     LatLng(position.target.latitude,
                    position.target.longitude))

    This object you may send to your server side and return response. Since we are using Getx, the response type would be Response object.

    If the reponse.body['status']==ok, then we will return the actual address.

    _address = response.body['results'][0]['formatted_address'].toString();

    Getting address from LatLng using google server, is also called Geocoding.

    After Geocoding, the address in string format could be in our UI.

     

    Flutter - Geolocator.getCurrentPosition never returns

     late Position _myPosition;
          Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
              .then((Position position) {
            _myPosition=position;
    
          print("Position "+_myPosition.toString());
          }).catchError((e) {
            _myPosition=Position(
              latitude: defaultLatLng != null ? defaultLatLng.latitude : double.parse( '0'),
              longitude: defaultLatLng != null ? defaultLatLng.longitude : double.parse( '0'),
              timestamp: DateTime.now(), accuracy: 1, altitude: 1, heading: 1, speed: 1, speedAccuracy: 1,
            );
            print("Error "+e);
          });

    It works

    Courses


    Recent posts