flutter-web: get location on web by Location plugin

4.5k Views Asked by At

I have old flutter project, I added web support to it, Now ,I am trying to get my Location in flutter web , So i added location to my page. this is my code:

  @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}");
    }
  }

After getting Location permission by chrome,

enter image description here

Nothing happening! In vsCode console i just got this error:

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

**USING @JS('navigator.geolocation')

I also try this, but never success method called and nothing heppen.

2

There are 2 best solutions below

0
On

Dart currently has an issue with the Geolocation API. Consider writing an interop library or using mine. Link below Geolocation PolyFill

0
On

This works now(all platforms including web), June 2021, with the Location package.

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

See full details here: pub.dev/packages/location