artistAhmed
artistAhmed

Reputation: 325

GeoLocation package doesn't work in flutter while running on a real device

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
//import 'package:provider/provider.dart';

class Map extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MapState();
}

class _MapState extends State<Map> {
  Completer<GoogleMapController> _controllerGoogleMap = Completer();
  GoogleMapController newGoogleMapController;

  Position currentPosition;
  var geoLocator = Geolocator();

  void locatePosition() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best);
    currentPosition = position;

    LatLng latLngPos = LatLng(position.latitude, position.longitude);

    CameraPosition cameraPosition =
        CameraPosition(target: latLngPos, zoom: 15.0);

    newGoogleMapController
        .animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: GoogleMap(
          mapType: MapType.normal,
          myLocationButtonEnabled: true,
          initialCameraPosition: _kGooglePlex,
          myLocationEnabled: true,
          zoomGesturesEnabled: true,
          zoomControlsEnabled: true,
          onMapCreated: (GoogleMapController controller) {
            _controllerGoogleMap.complete(controller);
            newGoogleMapController = controller;
            locatePosition();
          },
        ),
      ),
    );
  }
}

Under the debug terminal

Launching lib\main.dart on vivo 1906 in debug mode... 
lib\main.dart:1 √ Built build\app\outputs\flutter-apk\app-debug.apk. I/flutter ( 9154):
Observatory listening on ************************************ I/flutter ( 9613): 
Observatory listening on ************************************ E/flutter ( 9613): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception:
User denied permissions to access the device's location. E/flutter ( 9613): 
#0 MethodChannelGeolocator._handlePlatformException package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:199 
E/flutter ( 9613): #1 MethodChannelGeolocator.getCurrentPosition package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:
118 E/flutter ( 9613): <asynchronous suspension> E/flutter ( 9613): #2 _MapState.locatePosition package:donation_yoga/screens/maps.dart:
21 E/flutter ( 9613): <asynchronous suspension> E/flutter ( 9613):

I never denied permission my permission is on, Also the map don't show the my location button even though I have enabled it to get current location, just shows zoom in and out button and the map that's it.

Using Flutter 2.2.1 google_maps_flutter: ^2.0.6 geolocator: ^7.0.3

PS: I have tried location package but it throws a lot of errors such as location_web not found etc,

Upvotes: 0

Views: 1278

Answers (2)

Debasis Sil
Debasis Sil

Reputation: 631

For All Users Getting "Unhandled Exception: User denied permissions to access the device's location"

pubspec.yaml

Add geolocator: ^8.0.1 under dependencies:

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  geolocator: ^8.0.1

AndroidManifest.xml

You will see the following :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.get_weather">

Add the following under the above code:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.hardware.location.gps" />

main.dart

import 'package:flutter/material.dart';
import 'package:get_weather/screens/loading_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

loading_screen.dart

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

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

class _LoadingScreenState extends State<LoadingScreen> {
  void getLocation() 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.');
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    print(position);
  }

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

The code in loading_screen.dart will help you get the 'User denied permission' resolved.

Upvotes: 1

austin
austin

Reputation: 605

try adding the forceLocationManager clause to your function:

  void locatePosition() async {

  Position position = await Geolocator.getLastKnownPosition({ bool forceAndroidLocationManager = true}
    );
  currentPosition = position;


  LatLng latLngPos = LatLng(position.latitude, position.longitude);

  CameraPosition cameraPosition =
    CameraPosition(target: latLngPos, zoom: 15.0);

  newGoogleMapController
    .animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

also check your android manifest for location:

<manifest ... >
 <!-- To request foreground location access, declare one of these 
 permissions. -->
  <uses-permission 
  android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" 
 />
 </manifest>

also keep your desired accuracy low ,accuracy at best creates privacy chaos with the device ,so it requires additional steps

Upvotes: 0

Related Questions