flutter-geolocator icon indicating copy to clipboard operation
flutter-geolocator copied to clipboard

location not retrieved by geolocator

Open sami7568 opened this issue 4 years ago • 49 comments

geolocation.getCurrentLocation is not working in my flutter application.

i am using geolocator ^6.1.2 compileSdkVersion: 30 minSdkVersion: 21 targetSdkVersion: 30

sami7568 avatar May 07 '21 09:05 sami7568

Same here. But with latest version. It is stuck in await Geolocator.getCurrentPosition(); and never returns

afxgroup avatar May 10 '21 10:05 afxgroup

if i use ACCESS_FILE_LOCATION i can get the location while if i use ACCESS_COARSE_LOCATION nothing is returned in the android emulator an it remain stuck in getCurrentPosition().

I have the same issue from 7.0.0 version to 7.0.3 geolocator version

https://github.com/Baseflow/flutter-geolocator/issues/507

zs-dima avatar May 14 '21 18:05 zs-dima

Can you provide more information about the device you're using? Be more specific about the issue, by providing your flutter doctor -v and maybe some example code. I must mention that there are known issues with Xiaomi devices.

florissmit1 avatar May 21 '21 12:05 florissmit1

@florissmit1 thanks for reply I have this issue on default Android emulator as well.

zs-dima avatar May 21 '21 19:05 zs-dima



>flutter doctor -v
[√] Flutter (Channel dev, 2.3.0-12.1.pre, on Microsoft Windows [Version 10.0.19041.928], locale ru-RU)
    • Flutter version 2.3.0-12.1.pre at c:\...
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f9c825981c (3 days ago), 2021-05-18 14:07:52 -0700
    • Engine revision 26e217e6c3
    • Dart version 2.14.0 (build 2.14.0-edge.a527411e5100a0a4f48c4009087a1b988aa784af)

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at c:\...
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = C:\...
    • Java binary at: c:\...
    • Java version Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\...

[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.10.0 Preview 4.0)
    • Visual Studio at C:\...
    • Visual Studio Community 2019 version 16.10.31313.381
    • The current Visual Studio installation is a pre-release version. It may not be supported by Flutter yet.
    • Windows 10 SDK version 10.0.19041.0

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).

[√] IntelliJ IDEA Ultimate Edition (version 2019.3)
    • IntelliJ at C:\...
    • Flutter plugin version 43.0.3
    • Dart plugin version 193.6494.35

[√] IntelliJ IDEA Ultimate Edition (version 2021.1)
    • IntelliJ at C:\...
    • Flutter plugin version 56.0.5
    • Dart plugin version 211.7233

[√] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.19041.928]
    • Chrome (web)      • chrome  • web-javascript • Google Chrome 90.0.4430.212
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 90.0.818.62

zs-dima avatar May 21 '21 19:05 zs-dima

using latest version of geolocator and flutter but can,t get the location after applying this code 'await Geolocator.getCurrentPosition(); '

Archit-crypto avatar May 22 '21 14:05 Archit-crypto

i am also faced same issue, its work few days ago when i complete testing and today i m check its not work

Akash84016 avatar May 24 '21 10:05 Akash84016

I'm facing same issue on Samsung A21. Any possible fix?

iamEtornam avatar May 26 '21 02:05 iamEtornam

i have the same problem, " await Geolocator.getCurrentPosition(); " dont return Position, with mobile from honor8x

Anullos avatar May 26 '21 07:05 Anullos

same issue

kirill-plotnikov avatar May 31 '21 06:05 kirill-plotnikov

I have the same issue if my global location is active but "Use location in work profile" is off. It doesn't throw any error, just stucked.

Screenshot

[✓] Flutter (Channel stable, 2.2.1, on macOS 11.4 20F71 darwin-x64, locale fr-FR) • Flutter version 2.2.1 • Framework revision 02c026b03c (5 days ago), 2021-05-27 12:24:44 -0700 • Engine revision 0fdb562ac8 • Dart version 2.13.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3) • Android SDK at /Users/***/Library/Android/sdk • Platform android-30, build-tools 30.0.3 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264) • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 12.5, Build version 12E262 • CocoaPods version 1.10.1

[✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2) • Android Studio at /Applications/Android Studio.app/Contents • 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 • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.56.2) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.22.0

[✓] Connected device (2 available) • SM A530F (mobile) • android-arm64 • Android 9 (API 28) • Chrome (web) • chrome • web-javascript • Google Chrome 91.0.4472.77

geolocator: ^7.0.3

ghost avatar Jun 01 '21 16:06 ghost

I try set forceAndroidLocationManager to true and its working. Not sure why

Position position = await Geolocator.getCurrentPosition(forceAndroidLocationManager: true);

nikhiysham avatar Jun 02 '21 06:06 nikhiysham

@nikhiysham forceAndroidLocationManager:true does NOT work for my case

zs-dima avatar Jun 02 '21 06:06 zs-dima

I try set forceAndroidLocationManager to true and its working. Not sure why

Position position = await Geolocator.getCurrentPosition(forceAndroidLocationManager: true);

This is working. Use: Position position = await Geolocator.getCurrentPosition( forceAndroidLocationManager: true, desiredAccuracy: LocationAccuracy.best, );

anjanpatel79 avatar Jun 02 '21 09:06 anjanpatel79

I suggest looking at the Geolocator example application. For me it's working fine on Android emulator / Samsung / Oppo test device using flutter 2.2.1. @zs-dima also, you're using an unstable version of Flutter, can you try using a stable version of Flutter?

@sami7568 @zs-dima can you provide a code snippet of the code you're using to get the currentPosition?

florissmit1 avatar Jun 04 '21 07:06 florissmit1

This issue has been automatically closed because there has been no response to our request for more information from the original author. With only the information that is currently in the issue, we don't have enough information to take action. Please reach out if you have or find the answers we need so that we can investigate further.

no-response[bot] avatar Jun 04 '21 13:06 no-response[bot]

I have the exact same problem. It worked yesterday or the day before. Today await Geolocator.getCurrentPosition seems to do absolutely nothing. I changed nothing apart from updating flutter_map.

Why was this closed?

barbalex avatar Jun 08 '21 19:06 barbalex

So I saw that this bot seems more intelligent than expected. I will try to give you more information:

derterminePosition.dart:

import 'package:geolocator/geolocator.dart';

determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      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.');
  }

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  // use getPositionStream for updates
  return await Geolocator.getCurrentPosition();
}

locate.dart:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'determinePosition.dart';
import 'package:geolocator/geolocator.dart';
import 'package:flutter_map/flutter_map.dart';

class MapMenuLocate extends StatelessWidget {
  final MapController mapController;
  MapMenuLocate({required this.mapController});

  @override
  Widget build(BuildContext context) {
    final toggleButtonsSelected = <bool>[false].obs;

    return Container(
      color: Theme.of(context).primaryColor.withOpacity(0.2),
      child: ToggleButtons(
        children: [
          Tooltip(
              child: Icon(Icons.my_location),
              message: 'Pan to current location'),
        ],
        isSelected: toggleButtonsSelected,
        onPressed: (int index) async {
          print('pressed: $index');
          toggleButtonsSelected[index] = true;
          Timer(
            Duration(seconds: 1),
            () {
              toggleButtonsSelected[index] = false;
            },
          );
          Position? position;
          try {
            position = await determinePosition();
          } catch (e) {
            Get.snackbar(
              'Error accessing position',
              e.toString(),
              snackPosition: SnackPosition.BOTTOM,
            );
          }
          if (position?.latitude != null && position?.longitude != null) {
            mapController.move(
              LatLng(
                position?.latitude ?? 0,
                position?.longitude ?? 0,
              ),
              13,
            );
          }
        },
        direction: Axis.vertical,
        selectedColor: Colors.white,
        fillColor: Theme.of(context).primaryColor.withOpacity(0.5),
        selectedBorderColor: Theme.of(context).primaryColor,
        borderColor: Theme.of(context).primaryColor,
      ),
    );
  }
}

And here the widget that calls MapMenuLocate: (uses ToggleButtons even though it is a single button because this is a group of ToggleButtons and this is the only one with a single button)

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'determinePosition.dart';
import 'package:geolocator/geolocator.dart';
import 'package:flutter_map/flutter_map.dart';

class MapMenuLocate extends StatelessWidget {
  final MapController mapController;
  MapMenuLocate({required this.mapController});

  @override
  Widget build(BuildContext context) {
    final toggleButtonsSelected = <bool>[false].obs;

    return Container(
      color: Theme.of(context).primaryColor.withOpacity(0.2),
      child: ToggleButtons(
        children: [
          Tooltip(
              child: Icon(Icons.my_location),
              message: 'Pan to current location'),
        ],
        isSelected: toggleButtonsSelected,
        onPressed: (int index) async {
          print('pressed: $index');
          toggleButtonsSelected[index] = true;
          Timer(
            Duration(seconds: 1),
            () {
              toggleButtonsSelected[index] = false;
            },
          );
          Position? position;
          try {
            position = await determinePosition();
          } catch (e) {
            Get.snackbar(
              'Error accessing position',
              e.toString(),
              snackPosition: SnackPosition.BOTTOM,
            );
          }
          if (position?.latitude != null && position?.longitude != null) {
            mapController.move(
              LatLng(
                position?.latitude ?? 0,
                position?.longitude ?? 0,
              ),
              13,
            );
          }
        },
        direction: Axis.vertical,
        selectedColor: Colors.white,
        fillColor: Theme.of(context).primaryColor.withOpacity(0.5),
        selectedBorderColor: Theme.of(context).primaryColor,
        borderColor: Theme.of(context).primaryColor,
      ),
    );
  }
}

Do you need more info?

barbalex avatar Jun 08 '21 19:06 barbalex

@barbalex Thanks for the extensive information you provided. Your code seems good to me to be honest. Just to be sure, did you add:

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

to your AndroidManifest? And:

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>

To your info.plist? Also, are you able to provide your flutter doctor -v and which version of geolocator you're using?

florissmit1 avatar Jun 08 '21 20:06 florissmit1

@florissmit1 Yes I did.

It seems to be related with the (configuration of the?) virtual device used. My usually used one crashed yesterday and I started one I use rarely. Here it does not work. Even though a location is set.

I now wiped all user data from the usual one I use which enabled me to restart my app in it again. And now it works.

So it seems to have nothing to do with my code and neither with flutter-geolocator. Sorry for bugging you.

And thanks a lot for giving us this great tool!

barbalex avatar Jun 08 '21 20:06 barbalex

Have same 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)

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

fomekong83 avatar Jul 04 '21 01:07 fomekong83

had the same issue. when used on an emulator use an app that fakes location this fixed it for me, the built-in location changer of emulators does not work.

aozuraa avatar Nov 25 '21 09:11 aozuraa

had the same issue. when used on an emulator use an app that fakes location this fixed it for me, the built-in location changer of emulators does not work.

Can you please tell where can i get the app from? I am new into these environments and i have not been able to use geolocator in my emulator in few days and its bugging me a lot. No data is returned by await statement

cramble19 avatar Jan 21 '22 13:01 cramble19

Thanks for your email. I have solved it

On Fri, 21 Jan 2022, 6:48 pm cramble19, @.***> wrote:

had the same issue. when used on an emulator use an app that fakes location this fixed it for me, the built-in location changer of emulators does not work.

Can you please tell where can i get the app from? I am new into these environments and i have not been able to use geolocator in my emulator in few days and its bugging me a lot. No data is returned by await statement

— Reply to this email directly, view it on GitHub https://github.com/Baseflow/flutter-geolocator/issues/731#issuecomment-1018519869, or unsubscribe https://github.com/notifications/unsubscribe-auth/ANAUJ6UHRZTH2BUNYN7ZCOTUXFP2BANCNFSM44JN3QYQ . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you were mentioned.Message ID: @.***>

sami7568 avatar Jan 21 '22 13:01 sami7568

same issue

await Geolocator.getCurrentPosition(forceAndroidLocationManager: Platform.isAndroid);
print('over')
//over not presented;

device sony xperia B8342

Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 2.8.1, on macOS 11.6.1 20G224 darwin-x64, locale zh-Hans-CN) [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 13.2.1) [✓] Chrome - develop for the web [✓] Android Studio (version 2020.3) [✓] VS Code (version 1.64.2) [✓] Connected device (2 available)

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

tinvyhx avatar Mar 15 '22 10:03 tinvyhx

activar GPS en genymotion. image

rodgav avatar Mar 19 '22 15:03 rodgav

had the same issue, in my case it's because my device was not connected to the internet

your3i avatar Jul 15 '22 06:07 your3i

I had the same problem and since it doesn't show any errors, to solve it I include the method inside a Future.delayed, I determined a duration, and if there is no response, the application continues working normally

reschaefer avatar Dec 02 '22 18:12 reschaefer

Still now resolution for this?

EmmanuelO11 avatar Jan 07 '23 01:01 EmmanuelO11

I am facing the same issue any resolution?

beamlakTadesse avatar Jan 11 '23 13:01 beamlakTadesse