Home > front end >  Google Maps Camera not loading to saved LatLng coordinates in Flutter
Google Maps Camera not loading to saved LatLng coordinates in Flutter

Time:08-20

I am trying to load a Google Map widget to coordinates whose latitude and longitude are saved as double variables in a custom object called AddressObject. In the edit_address.dart I want to initState call the camera position to the saved location's coordinates. Here, editingAddress is an instance of AddressObject. I am calling the getSavedLocation method in initState but the camera would be stuck at (0,0).

Relevant Codes:

class AddressObject {
  String personName;
  //String? type;
  String addressLine1;
  String addressLine2;
  String? landmark;
  String city;
  String state;
  String pinCode;
  bool isCurrentAddress;
  double latitude;
  double longitude;
  AddressObject({
    required this.personName,
    //this.type,
    required this.addressLine1,
    required this.addressLine2,
    this.landmark,
    required this.city,
    required this.state,
    required this.pinCode,
    required this.isCurrentAddress,
    required this.latitude,
    required this.longitude,
  });
}

edit_address.dart

GoogleMapController? _googleMapController;
CameraPosition _cameraPosition = CameraPosition(target: LatLng(0, 0));
LatLng _latlong = LatLng(0, 0);

Future<void> getSavedLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled =
        await GeolocatorPlatform.instance.isLocationServiceEnabled();
    if (!serviceEnabled) {
      await GeolocatorPlatform.instance.openLocationSettings();
      return Future.error('Location services are disabled.');
    }

    permission = await GeolocatorPlatform.instance.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await GeolocatorPlatform.instance.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // position = await GeolocatorPlatform.instance.getCurrentPosition(
    //     locationSettings:
    //         const LocationSettings(accuracy: LocationAccuracy.high));

    _latlong =
        LatLng(widget.editingAddress.latitude, widget.editingAddress.longitude);

    setState(() {
      _googleMapController!.animateCamera(CameraUpdate.newCameraPosition(
          CameraPosition(target: _latlong, zoom: 15)));
      getAddress();
      print(
          "${widget.editingAddress.latitude}, ${widget.editingAddress.longitude}");
      print("${_latlong.latitude}, ${_latlong.longitude}");
    });

    //return position;
  }

List<Placemark>? placeMarks;

  getAddress() async {
    placeMarks =
        await placemarkFromCoordinates(_latlong.latitude, _latlong.longitude);
    Placemark placemark = placeMarks![0];
    // _addressController.text =
    //     "${placemark.street}, ${placemark.subLocality}, ${placemark.locality}, ${placemark.subAdministrativeArea}, ${placemark.postalCode}, ${placemark.country}";
    _addressLine1Controller.text =
        "${placemark.street}, ${placemark.subThoroughfare}";
    _addressLine2Controller.text = "${placemark.thoroughfare}";
    _landmarkController.text = "${placemark.subThoroughfare}";
    _cityController.text = "${placemark.subLocality}";
    _stateController.text = "${placemark.administrativeArea}";
    _pinCodeController.text = "${placemark.postalCode}";
  }

@override
  void initState() {
    super.initState();
    getSavedLocation();
    _personNameController.text = widget.editingAddress.personName;
    _addressLine1Controller.text = widget.editingAddress.addressLine1;
    _addressLine2Controller.text = widget.editingAddress.addressLine2;
    _landmarkController.text = widget.editingAddress.landmark!;
    _cityController.text = widget.editingAddress.city;
    _stateController.text = widget.editingAddress.state;
    _pinCodeController.text = widget.editingAddress.pinCode;
  }

I'm having the following code inside Widget build:

SizedBox(
                    width: screenWidth,
                    height: screenHeight * 0.225,
                    child: GoogleMap(
                      initialCameraPosition: _cameraPosition,
                      onMapCreated: (controller) {
                        setState(() {
                          _googleMapController = controller;
                        });
                      },
                      markers: Set<Marker>.of(<Marker>[
                        Marker(
                          markerId: MarkerId("1"),
                          position: _latlong,
                          icon: BitmapDescriptor.defaultMarkerWithHue(
                              BitmapDescriptor.hueRed),
                        ),
                      ]),
                      onCameraMove: (CameraPosition cameraposition) async {
                        _cameraPosition = cameraposition;
                        _latlong = LatLng(cameraposition.target.latitude,
                            cameraposition.target.longitude);
                        getAddress();
                      },
                    ),
                  ),

What is wrong with my code that is preventing the google maps camera to load to the saved location coordinates and how to solve the problem?

CodePudding user response:

Issue resolved when I uncommented the following lines in the getSavedAddress method:

// position = await GeolocatorPlatform.instance.getCurrentPosition(
    //     locationSettings:
    //         const LocationSettings(accuracy: LocationAccuracy.high));
  • Related