flutter-web:通过 Location 插件在网络上获取位置

标签 flutter location flutter-web getlocation

我有一个旧的 flutter 项目,我向它添加了 web 支持,现在,我试图在 flutter web 中获取我的位置,所以我添加了 location到我的页面。 这是我的代码:

  @override
  void initState() {
    super.initState();
    _getLocation();
  }

  Future _getLocation() async {
    Location location = new Location();

    var _permissionGranted = await location.hasPermission();
    _serviceEnabled = await location.serviceEnabled();

    if (_permissionGranted != PermissionStatus.granted || !_serviceEnabled) {
      _permissionGranted = await location.requestPermission();
      _serviceEnabled = await location.requestService();
    } else {
      print("-----> $_serviceEnabled");

      setState(() {
        _serviceEnabled = true;
        _loading = false;
      });
    }

    try {
      final LocationData currentPosition = await location.getLocation();
      setState(() {
        longitude = currentPosition.longitude.toString();
        latitude = currentPosition.latitude.toString();
        print(
            '${widget.url}?BranchName=&latitude=${latitude}&longitude=${longitude}');
        _loading = false;
      });
    } on PlatformException catch (err) {
      _loading = false;
      print("-----> ${err.code}");
    }
  }

通过chrome获取位置权限后,

enter image description here

什么都没发生! 在 vsCode 控制台中,我收到了这个错误:

Error: [object GeolocationPositionError]


    at Object.createErrorWithStack (http://localhost:43705/dart_sdk.js:4351:12)
    at Object._rethrow (http://localhost:43705/dart_sdk.js:37962:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:43705/dart_sdk.js:37956:13)
    at Object._microtaskLoop (http://localhost:43705/dart_sdk.js:37788:13)
    at _startMicrotaskLoop (http://localhost:43705/dart_sdk.js:37794:13)
    at http://localhost:43705/dart_sdk.js:33303:9

**使用@JS('navigator.geolocation')

我也是try this , 但从未调用过 success 方法,而且什么也没有。

最佳答案

现在(包括网络在内的所有平台),2021 年 6 月,使用 Location 包。

final Location location = new Location();
_locationData = await location.getLocation();
print(_locationData.latitude);

在此处查看完整详细信息: pub.dev/packages/location

关于flutter-web:通过 Location 插件在网络上获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64411270/

相关文章:

dart - 键盘显示时 Flutter Form 消失

sql - 雪花中的地理空间连接

ios - 在 iOS 中获取街道名称

flutter - SetOptions 在 Firestore Flutter WEB 中不起作用

flutter - 如何在 futureBuilder 中使用 'toIso8601String'

flutter - 显示文字取决于在flutter中的下拉菜单选择

flutter - 如何在父/根窗口小部件中初始化数据模型错误:只能在初始化程序中访问静态成员

Flutter web 在同一项目但不同的笔记本电脑上引发错误

Flutter 排序数据 Firestore 与 Streambuilder

ios - 检查定位服务是否开启