flutterdartgoogle-cloud-firestoregeolocationgeolocator

How to get latitude and longitude from Geolocator to Firestore location field


This is my function to get current location, using geolocator

import 'package:geolocator/geolocator.dart';

Future<Position> determinePosition() async {
  LocationPermission permission;

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.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 position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high);

  return position;
}

the function returns its Latitude and Longitude, however, I cannot assign it to the location field in Firestore

final crab = <String, Object>{
            "species": label,
            "edibility": edibility,
            "location": GeoPoint() // i want to put the result here,
            "timestamp": Timestamp.now()
          };

FirebaseFirestore.instance.collection('crabData').add(crab);

Solution

  • Your determinePosition returns a Position object, while Firestore expects a GeoPoint object. So you will have to convert information from the Position into a GeoPoint:

    let pos = await determinePosition();
    let loc = GeoPoint(pos.latitude, pos.longitude);
    

    After this, you can pass the loc into Firestore.