Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get user location through browser #392

Closed
lionelquirynen opened this issue Feb 13, 2020 · 32 comments · Fixed by #658
Closed

Get user location through browser #392

lionelquirynen opened this issue Feb 13, 2020 · 32 comments · Fixed by #658
Labels
platform: web Issue is related to the Web platform type: enhancement New feature or request

Comments

@lionelquirynen
Copy link

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 !

@mvanbeusekom mvanbeusekom added the type: question Issue contains a question about the project label Feb 14, 2020
@mvanbeusekom
Copy link
Member

mvanbeusekom commented Feb 14, 2020

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 mvanbeusekom added platform: web Issue is related to the Web platform type: enhancement New feature or request and removed type: question Issue contains a question about the project labels Feb 14, 2020
@lionelquirynen
Copy link
Author

lionelquirynen commented Feb 15, 2020

@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.

@xpat
Copy link

xpat commented Feb 22, 2020

@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?

@LarsHenning98
Copy link

LarsHenning98 commented Feb 26, 2020

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!

@lionelquirynen
Copy link
Author

lionelquirynen commented Feb 26, 2020

@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.

@lionelquirynen
Copy link
Author

@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 !

@xpat
Copy link

xpat commented Feb 28, 2020

@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

@lionelquirynen
Copy link
Author

Could you post your pubspec and your loading screen ?

@xpat
Copy link

xpat commented Feb 28, 2020

@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`

@xpat
Copy link

xpat commented Feb 28, 2020

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

@lionelquirynen
Copy link
Author

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

@xpat
Copy link

xpat commented Feb 28, 2020

@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.

@lionelquirynen
Copy link
Author

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

@xpat
Copy link

xpat commented Feb 28, 2020

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."

@lionelquirynen
Copy link
Author

Is your locationjs up to date ?

@xpat
Copy link

xpat commented Feb 28, 2020

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.

@lionelquirynen
Copy link
Author

lionelquirynen commented Feb 28, 2020 via email

@lionelquirynen
Copy link
Author

I mean the .dart

@lionelquirynen
Copy link
Author

lionelquirynen commented Feb 28, 2020

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

@xpat
Copy link

xpat commented Feb 28, 2020

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

@xpat
Copy link

xpat commented Feb 28, 2020

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

@lionelquirynen
Copy link
Author

Look at my code in github on how to use it

@xpat
Copy link

xpat commented Feb 28, 2020

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?

@lionelquirynen
Copy link
Author

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..

@xpat
Copy link

xpat commented Feb 29, 2020

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

@lionelquirynen
Copy link
Author

In the loading_screen ! Did you understand how it worked?

@xpat
Copy link

xpat commented Feb 29, 2020

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.

@xpat
Copy link

xpat commented Feb 29, 2020

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

@lionelquirynen
Copy link
Author

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

@mmcc007
Copy link

mmcc007 commented Aug 5, 2020

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.

@tazik561
Copy link

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

@arsamme
Copy link

arsamme commented Jan 4, 2021

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

@mvanbeusekom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
platform: web Issue is related to the Web platform type: enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants