Baseflow / flutter-geolocator

Android and iOS Geolocation plugin for Flutter
https://baseflow.com/
MIT License
1.25k stars 657 forks source link

Geolocator.getCurrentPosition() not returning location. #773

Closed fomekong83 closed 3 years ago

fomekong83 commented 3 years ago

ISSUE GETTING USER LOCATION

var location = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best,forceAndroidLocationManager: true);

not returning.

flutter doctor -v

[√] Flutter (Channel stable, 2.2.2, on Microsoft Windows [Version 10.0.19042.1052], locale en-US)
    • Flutter version 2.2.2 at C:\flutter
    • Framework revision d79295af24 (3 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.1)
    • Android SDK at C:\Users\***\AppData\Local\Android\sdk
    • Platform android-30, build-tools 30.0.1
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6842174)
    • All Android licenses accepted.

[X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[√] Android Studio
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • android-studio-dir = C:\Program Files\Android\Android Studio
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6842174)

[√] VS Code (version 1.57.1)
    • VS Code at C:\Users\***\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.14.1

[√] Connected device (2 available)
    • SM T550 (mobile) • 5f67f04a1ae7982d • android-arm    • Android 7.1.1 (API 25)
    • Edge (web)       • edge             • web-javascript • Microsoft Edge 91.0.864.59

! Doctor found issues in 1 category.

HERE IS MY CODE

Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    var location = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best,forceAndroidLocationManager: true);

    return location;
  }

THIS IS HOW I CALL IT

FutureBuilder(
                builder: (context,snapshot){
                  switch(snapshot.connectionState){
                    case ConnectionState.waiting: return Text("Loading Location");
                    default:
                      if (snapshot.hasError)
                        return Text('Error can\'t get your location: ${snapshot.error}');
                      else
                        return Text('Result: ${snapshot.data}');
                  }
                },
                future: _determinePosition(),
      ),

I ADDED THESE INTO MY ANDROID MANIFEST

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

I'M USING geolocator: ^7.2.0+1

MY GRADLE LOOKS LIKE THIS

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).

        minSdkVersion 20
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

I'M NEW IN THIS . HELP HELP

chainchelliah commented 3 years ago

I think everyone facing this issue. For me also not working. @mvanbeusekom any update or help on this?

mvanbeusekom commented 3 years ago

Hi @fomekong83, @chainchelliah,

Personally I think the problem is that your device doesn't get a good connection with the GPS satellites. I noticed that you are using the forceAndroidLocationManager: true parameter which means the geolocator will use the older Android LocationManager SDK. When you also specify the desiredAccuracy: LocationAccuracy.high or desiredAccuracy: LocationAccuracy.best this will result in the LocationManager trying to acquire the location using the GPS provider on the device. The problem is that the GPS provider requires a good connection with GPS satellites to acquire the location (usually this means you need to be outdoors).

To work around this you could specify a timeout and switch to LocationAccuracy.medium which will internally use the Network provider to determine the location which works better in situations where the GPS signal is not stable enough. Unfortunately we don't have an option to read the strength of the GPS signal to determine a more explicit way to switch providers.

I made a small test application based on the default Flutter template that I used to test the problem. If I run the App indoors, with the desiredAccuracy set to LocationAccuracy.best, the App keeps showing the "in progress" indicator until I move to a spot where I get a connection with GPS satellites. If I change the desiredAccuracy to LocationAccuracy.medium I receive a signal almost immediately.

Take the following steps if you would like to reproduce my test app:

  1. Create a new Flutter App: flutter create geo_issue_773;
  2. Add permissions to the android/app/main/src/AndroidManifest.xml file (see my copy below);
  3. Add dependency on the geolocator to the pubspec.yaml file (see my copy below);
  4. Replace the contents of the lib/main.dart with the version provided below.

After these steps run the App on your device and hit the "+" button to acquire a location. To change the accuracy update line 36.

AndroidManifest.xml ```xml ```
pubspec.yaml ```yaml name: geo_issue_773 description: A new Flutter project. publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter geolocator: ^7.2.0+1 cupertino_icons: ^1.0.2 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true ```
main.dart ```dart import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { Position? _position; bool _isLoading = false; Future _getPosition() async { Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.best, forceAndroidLocationManager: true, ).then((Position position) { print('Acquired position: $position'); setState(() { _position = position; _isLoading = false; }); }); setState(() { _isLoading = true; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: (_isLoading) ? CircularProgressIndicator() : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'The following position was acquired:', ), Text( '$_position', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _getPosition, tooltip: 'Increment', child: Icon(Icons.add), ), ); } } ```

I am going to close this issue as the geolocator is working correctly. If you have any questions or problems feel free to leave a comment and I will try my best to provide an answer.

jahnli commented 3 years ago

@mvanbeusekom But alas for China, that doesn't work

jahnli commented 3 years ago

@mvanbeusekom But alas for China, that doesn't work

MrWj commented 2 years ago

use LocationAccuracy.medium, It's It's a problem with GPS signals

zhangyin2019 commented 2 years ago

@MrWj tks

xyhuangjia commented 2 years ago

use LocationAccuracy.medium, It's It's a problem with GPS signals

so magic