3

I'm currently using the Flutter Geolocator Plugin to access user's location (latitude/longitude), but it seems like it does not work for the web yet. I tried to find something to retrieve the user's location in Flutter for web, but I couldn't find it.

Has anyone already tried/found something to do the job?

karel
  • 5,489
  • 46
  • 45
  • 50
lioleveau
  • 518
  • 1
  • 6
  • 23

1 Answers1

13

To be able to retrieve the position for the web part I had to use https://pub.dev/packages/js to expose the JavaScript API and combine it with https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API.

So here how it looks like :

  1. First create a file (ex: locationJs.dart) to expose the JS function :

     @JS('navigator.geolocation') // navigator.geolocation namespace
     library jslocation; // library name can be whatever you want
    
     import "package:js/js.dart";
    
    @JS('getCurrentPosition') // Accessing method getCurrentPosition 
    from       Geolocation API
    external void getCurrentPosition(Function success(GeolocationPosition pos));
    
    @JS()
    @anonymous
    class GeolocationCoordinates {
      external double get latitude;
      external double get longitude;
      external double get altitude;
      external double get accuracy;
      external double get altitudeAccuracy;
      external double get heading;
      external double get speed;
    
    external factory GeolocationCoordinates(
      {double latitude,
      double longitude,
      double altitude,
      double accuracy,
      double altitudeAccuracy,
      double heading,
      double speed});
      }
    
    @JS()
    @anonymous
    class GeolocationPosition {
    external GeolocationCoordinates get coords;
    
    external factory GeolocationPosition({GeolocationCoordinates 
    coords});
    }
    
  2. Call the newly created file

     import 'package:Shared/locationJs.dart';
    
      success(pos) {
         try {
           print(pos.coords.latitude);
           print(pos.coords.longitude);
           } catch (ex) {
            print("Exception thrown : " + ex.toString());
             }
         }
    
      _getCurrentLocation() {
          if (kIsWeb) {
            getCurrentPosition(allowInterop((pos) => success(pos)));
                    }
          }
    
JMP
  • 4,417
  • 17
  • 30
  • 41
lioleveau
  • 518
  • 1
  • 6
  • 23
  • 1
    Thanks a lot been looking for this – matshidis Apr 30 '20 at 16:39
  • 1
    Can you help me please? Im getting the error: "NoSuchMethodError: tried to call a non-function, such as null: 'geolocation.getCurrentPosition'" – Pablo Cegarra Jun 10 '20 at 06:56
  • Hi.. this is great answer, and it works for me... can you provide me a guidance about the start the way you create locationJs.dart dan combine it with api js ? – wahyu Sep 16 '20 at 02:58
  • This is not work https://stackoverflow.com/questions/64411270/flutter-web-get-location-on-web-by-location-plugin – Cyrus the Great Oct 18 '20 at 09:20