how to set distance between users using Geolocator in flutter

坚强是说给别人听的谎言 提交于 2021-02-11 13:46:31

问题


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();
                    })
              ],
            );
          });
    }
  }

回答1:


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.



来源:https://stackoverflow.com/questions/61230131/how-to-set-distance-between-users-using-geolocator-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!