0

I can figure out how to get the user's latitude and longitude together, but need to get them individually to utilise the Geolocator().distanceBetween function from the Geolocator package. My code below keeps getting the error:

Unhandled Exception: NoSuchMethodError: The getter 'latitude' was called on null.

Receiver: null

Tried calling: latitude

  Future<Position> getLocation() async {
    var currentLocation;
    try {
      currentLocation = await geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.best);
    } catch (e) {
      currentLocation = null;
    }
    return currentLocation;
  }


  void calculateDistance() async {

    getLocation().then((position) {
       userLocation = position;
    });

      final double myPositionLat =  userLocation.latitude;
      final double myPositionLong = userLocation.longitude;

      final double TPLat = 51.5148731;
      final double TPLong = -0.1923663;
      final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;

      print(distanceInMetres);

  }

1 Answer 1

1

Try this :

void calculateDistance() async {

getLocation().then((position) {
   userLocation = position;


  final double myPositionLat =  userLocation.latitude;
  final double myPositionLong = userLocation.longitude;

  final double TPLat = 51.5148731;
  final double TPLong = -0.1923663;
  final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;

  print(distanceInMetres);

  });
}

or another way of doing this is :

void calculateDistance() async {

userLocation = await getLocation();


  final double myPositionLat =  userLocation.latitude;
  final double myPositionLong = userLocation.longitude;

  final double TPLat = 51.5148731;
  final double TPLong = -0.1923663;
  final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;

  print(distanceInMetres);
}
1
  • Broooo you saved me Commented Mar 24, 2020 at 19:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.