wahyu
wahyu

Reputation: 2405

how to set distance between users using Geolocator in flutter

I am currently trying to give access to users to do something when users are in radius x meters from position that I have determined. So, what I mean is.. I declare a position with x latitude and y longitude.. and then if users position is 500 meters from position that I have declare, they can access something else... is there a way to do that? here is part of my code

Position _mine;
  Future _searchMe() async {
    if ((await Geolocator().isLocationServiceEnabled())) {
      final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
      geolocator
          .getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
          .then((Position position) {
        setState(() {
          _mine = position;
        });
        print(_mine.latitude);
      }).catchError((err) {
        print(err);
      });
    } else {
      print("ok");
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              content:
                  const Text('Make sure your GPS is on !'),
              actions: <Widget>[
                FlatButton(
                    child: Text('ok'),
                    onPressed: () {
                      Navigator.of(context, rootNavigator: true).pop();
                    })
              ],
            );
          });
    }
  }

Upvotes: 0

Views: 2257

Answers (1)

Sukhi
Sukhi

Reputation: 14195

You can probably do something like below :

double _countDistance(double userLatitude, double userLongitude) {
    return Distance().as(
      LengthUnit.Kilometer,
      LatLng(declaredLocation.latitude, declaredLocation.longitude),
      LatLng(userLatitude, userLongitude),
    );
  }

Exaplanation :

The Distance().as method takes three parameters : A. unit e.g. kilometer, meter etc. B. first lat-long C. second lat-long

The above function would calculate the distance in km. You can add this code in yours and do something when the user is within 500 meters.

Upvotes: 2

Related Questions