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

Location is not retrieved by Geolocator

Open wagnerdelima opened this issue 7 years ago • 20 comments

💬 Questions and Help

Hello,

I've been using geolocator and ever since the update to version 3.0.0 geolocator can no longer retrieve the location.

I am using the correct dependencies:

dependencies: geolocator: '^3.0.0'

targetSdkVersion 28 and compileSdkVersion 28

Flutter doctor gives me this: ` [✓] Flutter (Channel stable, v1.0.0, on Mac OS X 10.14.3 18D109, locale en-US) [✓] Android toolchain - develop for Android devices (Android SDK 28.0.3) [✓] iOS toolchain - develop for iOS devices (Xcode 10.1) [✓] Android Studio (version 3.2) [✓] IntelliJ IDEA Community Edition (version 2018.2.5) [✓] Connected device (1 available)

• No issues found!`

Once I call await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high); the code just doesn't return anything and I have this output in terminal:

I/DynamiteModule( 4233): Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:221 I/DynamiteModule( 4233): Selected remote version of com.google.android.gms.maps_dynamite, version >= 221 V/DynamiteModule( 4233): Dynamite loader version >= 2, using loadModule2NoCrashUtils W/System ( 4233): ClassLoader referenced unknown path: W/System ( 4233): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000030/n/armeabi-v7a W/System ( 4233): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000030/n/armeabi I/Google Maps Android API( 4233): Google Play services client version: 12451000 I/Google Maps Android API( 4233): Google Play services package version: 15090018 W/DynamiteModule( 4233): Local module descriptor class for com.google.android.gms.googlecertificates not found. I/DynamiteModule( 4233): Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4 I/DynamiteModule( 4233): Selected remote version of com.google.android.gms.googlecertificates, version >= 4 W/System ( 4233): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/0000002f/n/armeabi-v7a W/System ( 4233): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/0000002f/n/armeabi

I id set the meta tags <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

and the <meta-data android:name="com.google.android.geo.API_KEY" android:value="my key here"/>

Would anybody be able to help me, please?

I have spent a considerable amount of time on this. I am new to flutter and know that I may be missing a small thing to make it work. Thanks a lot folks. For questions or help we recommend checking:

wagnerdelima avatar Feb 20 '19 09:02 wagnerdelima

Any news on this?

wagnerdelima avatar Feb 20 '19 16:02 wagnerdelima

@wagnerdelima could you check with version 3.0.1?

If you are still having problems, can you confirm if you experience the same issues in the example app of the Geolocator plugin (we are having a hard time reproducing the issue)?

mvanbeusekom avatar Mar 05 '19 12:03 mvanbeusekom

I'm having the same problem. I just installed the 3.0.1 (also tried the 3.0.0) and put use_frameworks on Podfile as I saw in one of the issues related to building problem.

When I call Geolocator().getCurrentPosition() it never returns the promise. If call again it tells me there is a permission request happening and that I can't ask more than once. But it never appears the permission request on the device. Even if I allow the location permission to always it doesn't work

My podfile:

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exists? file_abs_path
    return [];
  end
  pods_ary = []
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) { |line|
      next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
      plugin = line.split(pattern=separator)
      if plugin.length == 2
        podname = plugin[0].strip()
        path = plugin[1].strip()
        podpath = File.expand_path("#{path}", file_abs_path)
        pods_ary.push({:name => podname, :path => podpath});
      else
        puts "Invalid plugin specification: #{line}"
      end
  }
  return pods_ary
end

target 'Runner' do
  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  use_frameworks! # required by Geolocator
  system('rm -rf .symlinks')
  system('mkdir -p .symlinks/plugins')

  # Flutter Pods
  generated_xcode_build_settings = parse_KV_file('./Flutter/Generated.xcconfig')
  if generated_xcode_build_settings.empty?
    puts "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first."
  end
  generated_xcode_build_settings.map { |p|
    if p[:name] == 'FLUTTER_FRAMEWORK_DIR'
      symlink = File.join('.symlinks', 'flutter')
      File.symlink(File.dirname(p[:path]), symlink)
      pod 'Flutter', :path => File.join(symlink, File.basename(p[:path]))
    end
  }

  # Plugin Pods
  plugin_pods = parse_KV_file('../.flutter-plugins')
  plugin_pods.map { |p|
    symlink = File.join('.symlinks', 'plugins', p[:name])
    File.symlink(p[:path], symlink)
    pod p[:name], :path => File.join(symlink, 'ios')
  }
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
      config.build_settings['SWIFT_VERSION'] = '4.0' # I tried delething this line and chaning to 4.2. It didn't work at any case
    end
  end
end

I also added this on my Info.plist:

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

felpsio avatar Mar 08 '19 18:03 felpsio

I just figured out the problem. It was something related to the Info.plist

I update the permission requests to:

<key>NSLocationWhenInUseUsageDescription</key>
	<string>When in use permissions</string>
	<key>NSLocationAlwaysUsageDescription</key>
	<string>always permissions</string>
	<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
	<string>Always and in usage permissions</string>

I also tried take off the line 'config.build_settings['SWIFT_VERSION'] = '4.0'' from my Podfile and stills working. I can't build without the line use_frameworks! # required by Geolocator. I think it's important to add this on the docs. I only figured out that I had to add this line after some time researching the issues

felpsio avatar Mar 08 '19 18:03 felpsio

use version 3.0.1 report [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(PERMISSION_DISABLED, Location data is not available on device, null)

loyasto avatar Apr 14 '19 12:04 loyasto

Any update on this?

I need to implement this ASAP. I there something that I can do to help solve this issue?

pedromassango avatar Jun 10 '19 08:06 pedromassango

Aqui está o problema

no arquivo Geolocator (5.1.5), na linha 205

está desta formar

void _handleInvalidPermissions(PermissionStatus permission) {
    if (permission == PermissionStatus.denied) {
      throw PlatformException(
          code: 'PERMISSION_DENIED',
          message: 'Access to location data denied',
          details: null);
    }
  }

o arquivo está retornando uma Exception, quando deveria retorna ou NULL ou a própria permission. segue arquivo corrigido

_handleInvalidPermissions(PermissionStatus permission) {
    if (permission == PermissionStatus.denied) {
      return permission;
    }
  }

hevertonpablo avatar Dec 05 '19 16:12 hevertonpablo

I am closing this issue as I am not using Flutter any more. Having a solution 10 months later is not sustainable. Thank you all for your efforts towards this.

wagnerdelima avatar Dec 09 '19 08:12 wagnerdelima

@wagnerdelima you can keep this opened as it was not fixed yet. My workaround was to:

  1. Use another package to check and request the location permission.
  2. Use this package to retrieve the current location only if permission was granted in step 1.

pedromassango avatar Dec 11 '19 11:12 pedromassango

Get the instance of Geolocator forcing Android Location Manager and after call the getCurrentPosition on this. In this way you can use the LocationManager plugin instead the default FusedLocationProviderClient plugin to retrieve the position.

Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true; Position position = await geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low);

nixonoftheyear avatar Jan 13 '20 09:01 nixonoftheyear

@SivaCorp THANK YOU SOOOOO MUCH

buildwithmalik avatar Mar 17 '20 14:03 buildwithmalik

You can see this issue complete solution of this problem is provided here https://github.com/Baseflow/flutter-geolocator/issues/434#issuecomment-631508832

Bhavya-Budhia avatar May 22 '20 16:05 Bhavya-Budhia

Get the instance of Geolocator forcing Android Location Manager and after call the getCurrentPosition on this. In this way you can use the LocationManager plugin instead the default FusedLocationProviderClient plugin to retrieve the position.

Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true; Position position = await geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low);

It saves my day. Thanks, man.

AhmedDiderRahat avatar Aug 13 '20 15:08 AhmedDiderRahat

Get the instance of Geolocator forcing Android Location Manager and after call the getCurrentPosition on this. In this way you can use the LocationManager plugin instead the default FusedLocationProviderClient plugin to retrieve the position.

Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true; Position position = await geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low);

This Worked

akhilpaulson avatar Aug 23 '20 18:08 akhilpaulson

Get the instance of Geolocator forcing Android Location Manager and after call the getCurrentPosition on this. In this way you can use the LocationManager plugin instead the default FusedLocationProviderClient plugin to retrieve the position. Geolocator geolocator = Geolocator()..forceAndroidLocationManager = true; Position position = await geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low);

It saves my day. Thanks, man.

I am getting an error that says The setter 'forceAndroidLocationManager' isn't defined for the type 'Geolocator'.

shrishti08 avatar Nov 28 '20 14:11 shrishti08

@shrishti08 since version 6.0.0 the forceAndroidLocationManager property has been removed.

Instead you can now supply this as a parameter to the getCurrentPosition and getPositionStream methods.

mvanbeusekom avatar Nov 28 '20 14:11 mvanbeusekom

@mvanbeusekom I have problem to retrieve coordinates from getCurrentPosition and getPositionStream with and without forceAndroidLocationManager when I don't have connection to Internet,

I'm using Geolocator 6.1.9, currently I'm test in a Pixel 2 XL Android 11 physical device, when I'm call this function the catch of LocationServiceDisabled is called, but if I check with await Geolocator.isLocationServiceEnabled() this return true.

Btw also I try with Iphone device and this works well, I'm using the example code with compileSDKVersion 30

Example Code
import 'dart:async';
import 'dart:math';

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: 'Material App', home: GeolocatorWidget());
  }
}

/// Example [Widget] showing the functionalities of the geolocator plugin
class GeolocatorWidget extends StatefulWidget {
  @override
  _GeolocatorWidgetState createState() => _GeolocatorWidgetState();
}

class _GeolocatorWidgetState extends State<GeolocatorWidget> {
  final List<_PositionItem> _positionItems = <_PositionItem>[];
  StreamSubscription<Position> _positionStreamSubscription;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:
          Colors.primaries[Random().nextInt(Colors.primaries.length)],
      body: ListView.builder(
        itemCount: _positionItems.length,
        itemBuilder: (context, index) {
          final positionItem = _positionItems[index];

          if (positionItem.type == _PositionItemType.permission) {
            return ListTile(
              title: Text(positionItem.displayValue,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  )),
            );
          } else {
            return Card(
              child: ListTile(
                title: Text(
                  positionItem.displayValue,
                ),
              ),
            );
          }
        },
      ),
      floatingActionButton: Stack(
        children: <Widget>[
          Positioned(
            bottom: 80.0,
            right: 10.0,
            child: FloatingActionButton.extended(
              onPressed: () async {
                await Geolocator.requestPermission();
                await Geolocator.getLastKnownPosition().then((value) => {
                      _positionItems.add(_PositionItem(
                          _PositionItemType.position, value.toString()))
                    });
                setState(
                  () {},
                );
              },
              label: Text("getLastKnownPosition"),
            ),
          ),
          Positioned(
            bottom: 10.0,
            right: 10.0,
            child: FloatingActionButton.extended(
                onPressed: () async {
                  await Geolocator.requestPermission();
                  print(await Geolocator.isLocationServiceEnabled());
                  await Geolocator.getCurrentPosition(
                          forceAndroidLocationManager: true,
                          desiredAccuracy: LocationAccuracy.low,
                          timeLimit: Duration(seconds: 30))
                      .then((value) => {
                            _positionItems.add(_PositionItem(
                                _PositionItemType.position, value.toString()))
                          });

                  setState(
                    () {},
                  );
                },
                label: Text("getCurrentPosition")),
          ),
          Positioned(
            bottom: 150.0,
            right: 10.0,
            child: FloatingActionButton.extended(
              onPressed: _toggleListening,
              label: Text(() {
                if (_positionStreamSubscription == null) {
                  return "getPositionStream = null";
                } else {
                  return "getPositionStream ="
                      " ${_positionStreamSubscription.isPaused ? "off" : "on"}";
                }
              }()),
              backgroundColor: _determineButtonColor(),
            ),
          ),
          Positioned(
            bottom: 220.0,
            right: 10.0,
            child: FloatingActionButton.extended(
              onPressed: () => setState(_positionItems.clear),
              label: Text("clear positions"),
            ),
          ),
          Positioned(
            bottom: 290.0,
            right: 10.0,
            child: FloatingActionButton.extended(
              onPressed: () async {
                await Geolocator.checkPermission().then((value) => {
                      _positionItems.add(_PositionItem(
                          _PositionItemType.permission, value.toString()))
                    });
                setState(() {});
              },
              label: Text("getPermissionStatus"),
            ),
          ),
        ],
      ),
    );
  }

  bool _isListening() => !(_positionStreamSubscription == null ||
      _positionStreamSubscription.isPaused);

  Color _determineButtonColor() {
    return _isListening() ? Colors.green : Colors.red;
  }

  void _toggleListening() {
    if (_positionStreamSubscription == null) {
      final positionStream = Geolocator.getPositionStream();
      _positionStreamSubscription = positionStream.handleError((error) {
        _positionStreamSubscription.cancel();
        _positionStreamSubscription = null;
      }).listen((position) => setState(() => _positionItems.add(
          _PositionItem(_PositionItemType.position, position.toString()))));
      _positionStreamSubscription.pause();
    }

    setState(() {
      if (_positionStreamSubscription.isPaused) {
        _positionStreamSubscription.resume();
      } else {
        _positionStreamSubscription.pause();
      }
    });
  }

  @override
  void dispose() {
    if (_positionStreamSubscription != null) {
      _positionStreamSubscription.cancel();
      _positionStreamSubscription = null;
    }

    super.dispose();
  }
}

enum _PositionItemType {
  permission,
  position,
}

class _PositionItem {
  _PositionItem(this.type, this.displayValue);

  final _PositionItemType type;
  final String displayValue;
}

hectorAguero avatar Dec 01 '20 17:12 hectorAguero

@shrishti08 since version 6.0.0 the forceAndroidLocationManager property has been removed.

Instead you can now supply this as a parameter to the getCurrentPosition and getPositionStream methods.

can u plss explain this in detail of wat to use instead as i am new to flutter i hv used ..........Future getLocation() async { try { Geolocator geoloc = Geolocator(); geoloc.forceAndroidLocationManager = true; /* wait for the position before continuing */ Position pos = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low);

and i am getting a red line on forceAndroidLocationManager saying error as The setter 'forceAndroidLocationManager' isn't defined for the type 'Geolocator'. Try importing the library that defines 'forceAndroidLocationManager', correcting the name to the name of an existing setter, or defining a setter or field named 'forceAndroidLocationManager'.

aditikumar-png avatar Dec 18 '20 12:12 aditikumar-png

@shrishti08 since version 6.0.0 the forceAndroidLocationManager property has been removed. Instead you can now supply this as a parameter to the getCurrentPosition and getPositionStream methods.

can u plss explain this in detail of wat to use instead as i am new to flutter i hv used ..........Future getLocation() async { try { Geolocator geoloc = Geolocator(); geoloc.forceAndroidLocationManager = true; /* wait for the position before continuing */ Position pos = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low);

and i am getting a red line on forceAndroidLocationManager saying error as The setter 'forceAndroidLocationManager' isn't defined for the type 'Geolocator'. Try importing the library that defines 'forceAndroidLocationManager', correcting the name to the name of an existing setter, or defining a setter or field named 'forceAndroidLocationManager'.

Instead of using Geolocator package switch to Location package. [https://pub.dev/packages/location]. The location package is much better and you will not face any difficulty. The function is as follows: Future getCurrentLocation() async { try { Location location = Location(); LocationData locationData; locationData = await location.getLocation(); long = locationData.longitude; lat = locationData.latitude; } catch (e) { print(e); } }

shrishti08 avatar Dec 18 '20 12:12 shrishti08

@shrishti08 since version 6.0.0 the forceAndroidLocationManager property has been removed. Instead you can now supply this as a parameter to the getCurrentPosition and getPositionStream methods.

can u plss explain this in detail of wat to use instead as i am new to flutter i hv used ..........Future getLocation() async { try { Geolocator geoloc = Geolocator(); geoloc.forceAndroidLocationManager = true; /* wait for the position before continuing */ Position pos = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.low); and i am getting a red line on forceAndroidLocationManager saying error as The setter 'forceAndroidLocationManager' isn't defined for the type 'Geolocator'. Try importing the library that defines 'forceAndroidLocationManager', correcting the name to the name of an existing setter, or defining a setter or field named 'forceAndroidLocationManager'.

Instead of using Geolocator package switch to Location package. [https://pub.dev/packages/location]. The location package is much better and you will not face any difficulty. The function is as follows: Future getCurrentLocation() async { try { Location location = Location(); LocationData locationData; locationData = await location.getLocation(); long = locationData.longitude; lat = locationData.latitude; } catch (e) { print(e); } }

Thank you so much!!!

aditikumar-png avatar Dec 18 '20 12:12 aditikumar-png