Flutter-geolocator: Get user location through browser

Created on 13 Feb 2020  Â·  32Comments  Â·  Source: Baseflow/flutter-geolocator

Hi, I was wondering if this plugins allowed to get the user's location through the browser? I did not find any informations about it ? Is there another plugins who allows it? Thanks in advance for the help !

web enhancement

Most helpful comment

@mvanbeusekom If I find some time to learn how to do it I could give it a try. Right now I found a way to do it via the js package. I post quickly the code here if someone wants it right away :

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

And to call this :  

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

You just have to call the method _getCurrentLocation.

All 32 comments

Hi @lionelquirynen, at the moment we do not have an implementation for the web platform. We would like to support this and are open for pull requests.

For future reference here are two article from the Flutter team describing how to add Web support to plugins:

@mvanbeusekom If I find some time to learn how to do it I could give it a try. Right now I found a way to do it via the js package. I post quickly the code here if someone wants it right away :

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

And to call this :  

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

You just have to call the method _getCurrentLocation.

@lionelquirynen Can you post your pubspec.yaml? I'm trying to add the line: import 'package:Shared/locationJs.dart'; as you posted it on stackexchange, but I'm getting errors. Did you create a Shared folder at the root level?

Hello @lionelquirynen!

First, I want to thank you for posting your solution here. I think you helped a lot of people with your message!

However, I still had two questions. You may also have come across these problems and already have a solution.
My questions are:

1.) Have you already found a way to ask visitors of the website for permission to query their location?
For apps you do this for Android under AndroidManifest.xml and for iOs under info.plist. But how do I do that for a web application?

2.) Have you already built a function that calculates the distance between two points in meters?

I would definitely be happy if you would answer! You would help me very much!

@xpat yes I've a folder where the locationJs file is located, sorry I just saw your message today.
For the pubspec, nothing change, you just have to add the js package to it.

@LarsHenning98
Hi,

1) With the code that I posted, it's working well to ask permission for web ! If you use this code for web, it will ask the permission automatically, You can give it a try in my mock project if you want : https://www.nearysport.com/
2) Yes but you have to do it server side, client-side you retrieve the latitute and longitude from the user and then you calculate the distance between two geolocation points with for example Haversine Formula.

Let me know if I answered your question !

@lionelquirynen Thanks, I'm running around in circles trying to figure out how to make this work for a class project. I've got the pubspec.yaml working and I've imported the file locationJS.dart in my loading_screen.dart file. Anyway, perhaps you're able to easily see how to make this work. Meanwhile, I'll keep plugging away. Here's a link to the message I posted on the class bulletin board: https://www.appbrewery.co/courses/548873/lectures/9989052/comments/5326630

FYI @LarsHenning98

Could you post your pubspec and your loading screen ?

@lionelquirynen Yes, the pubspec: `name: clima
description: A new Flutter application.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  geolocator: ^5.3.0
  js: ^0.6.1+1

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

  assets:
  - images/

  fonts:
  - family: Spartan MB
    fonts:
    - asset: fonts/SpartanMB-Black.otf
      weight: 900`

@lionelquirynen and the loading_screen.dart:

import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:clima/locationJS.dart';
import 'package:js/js.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  void getCurrentPosition() async {
    Position position = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.low);

    print(position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
// Get the current location
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

You dont call the method, thats why, you should put it in InitState

@lionelquirynen Thanks for the help. I hate to have to rely on you (or anyone else), but I'm still confused about which file to put it in or call it from. Here's a link to the full project.. And this comes from the 13th module in the Complete Flutter Development Bootcamp, which unfortunately was made before flutter web.

You could call the method getcurrentposition in onpressed because I dont see anywhere the call to the method, you should call it somewhere to trigger the location request

That's where I'm getting stuck. I just updated the loading_screen.dart file in case you want to take a look at what I'm trying, based on how I understand your suggestion. In Dart Analysis I'm getting an info message: "The declaration ' getCurrentPosition' isn't referenced, and that the packages js.dart and clima/locationJS.dart aren't used, and then the print(value.coords.latitude) and the print(value.coords.longitude) are underlined grey squiggly and the message reads "Set literals weren't support until version 2.2, but this code is required to be able to run on earlier versions."

Is your locationjs up to date ?

I'm using the code you published on stackoverflow, if that's what you mean? I'll run flutter pub get again, but yes, I believe it is up to date.

Did you paste the code from github not stackoverflow ?

Le ven. 28 févr. 2020 à 21:53, Christophe R. Patraldo <
[email protected]> a écrit :

I'll run flutter pub get again, but yes, I believe it is up to date.

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/Baseflow/flutter-geolocator/issues/392?email_source=notifications&email_token=ANUIRZMOEPTHHNBI7NDU3G3RFF2TJA5CNFSM4KURNFD2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOENKDZHY#issuecomment-592723103,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ANUIRZLLEKQ2CKHF2A7VUIDRFF2TJANCNFSM4KURNFDQ
.

I mean the .dart

You should use the code I posted on github, above. I Should update my answer on stackoverflow.

I focused on the stackoverflow code because it was easier to grasp. But now I've updated the loading_screen.dart and the locationJS.dart files with your code from Github. I'm getting errors Undefined name 'pos' and the method 'success' isn't defined for the class '_LoadingScreenState' and the method '_getCurrentLocation' isn't defined for the class '_LoadingScreenState.'

@JS('navigator.geolocation')
library jslocation;

import 'package:js/js.dart';

@JS('getCurrentPosition')
external void getPosition(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({GeolcationCoordinates});
}
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:clima/locationJS.dart';
import 'package:js/js.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  void getCurrentPosition() async {
      success(pos);
      try
          {
            print(pos.coords.latitude);
            print(pos.coords.longitude);
          } catch (ex) {
        print("Exception thrown: " + ex.toString());
      }
    }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
// Get the current location
         _getCurrentLocation();

          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

Look at my code in github on how to use it

The errors I'm getting are after I've used the code you posted on Github (above). I've been at a loss as to how exactly to add that code to my project (which I'm building with flutter web). For instance, where do I put the part that begins with success? I tried putting it here:

class _LoadingScreenState extends State {
void getCurrentPosition() async {
success(pos);
try
{

Do you have a public repository with your complete project code?

No it's not public but above I posted the code :

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)));
}else{
//Get location Ios Android
}
}

So you copy paste this code and all you have to do is to call _getCurrentLocation() in your onPressed method..

Does this code go in the locationJS.dart file or the loading_screen.dart?

`And to call this :

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)));
}`

In the loading_screen ! Did you understand how it worked?

I may be getting there. I just had Dart Analysis (Android Studio) create Function Function(GeoLocationPosition pos) get success => null; I'll see what I can make of that. But no, I don't really have a grasp of what's going on. This problem -- getting geolocation for the web -- has been a real challenge for me. At times I feel as if I have learned only the bare minimum in my Flutter Bootcamp.

So when I add the lines that begin with success, well it's completely trial and error. I don't know where to put them.

I'm making progress. I finally got the code to pop up a permission's window. And it's printing a message to the console. Thanks for your help and encouragement. I think it's finally starting to work, and once it does, I'll try and make sense of it. Hopefully this geolocator plugin will be updated for flutter web. Meanwhile, thanks again for your time, @lionelquirynen

Ok perfect ! Hope u don't get too confused, let me know if you need guidance !

Here is a working implementation for web:
https://github.com/AseemWangoo/experiments_with_web
https://fir-signin-4477d.firebaseapp.com/#/location (while up)
Could be integrated as a plugin or as is. If as is, use kIsWeb.

I want to get user location on flutter web but Mozilla GeoLocation not work !!!Can some one help me?
This is my question on StackOverFlow: https://stackoverflow.com/questions/64411270/flutter-web-get-location-on-web-by-location-plugin

Is there any news or anything about web support of this package?!

@mvanbeusekom

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jaumard picture jaumard  Â·  3Comments

Andrew-Tolentino picture Andrew-Tolentino  Â·  3Comments

seakmengc picture seakmengc  Â·  3Comments

prasant10050 picture prasant10050  Â·  6Comments

deisold picture deisold  Â·  3Comments