Nikash Deka
Nikash Deka

Reputation: 427

Not able to get the Latitude and Longitude while using 'GeoLocator' package

  1. I am trying to use 'GeoLocator' to retrieve Latitude & Longitude. However, not able to get any output?

  2. Also will be helpful if someone can help me organize the 'geoLocator' package as a service in a separate dart file.

  3. As suggested I tried changing the code, but still not able to get the geolocation. Also when I call the '_determinePosition()' getting "Instance of 'Future' ".

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //

  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.deniedForever) {
        // Permissions are denied forever, handle appropriately.
        return Future.error(
            'Location permissions are permanently denied, we cannot request permissions.');
      }

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

    return await Geolocator.getCurrentPosition();
  }

  @override
  Widget build(BuildContext context) {
    // TESTIST IF PRINT CAN WORK HERE
    print(_determinePosition());
    return Scaffold(
      appBar: AppBar(
        title: Text("Location"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              child: Text("Get location"),
              onPressed: () {
                // PRINTING IN THE CONSOLE
                _determinePosition();
              },
            ),
          ],
        ),
      ),
    );
  }
}

Upvotes: 2

Views: 893

Answers (2)

sempernoob
sempernoob

Reputation: 186

Try to add the Internet permission in addition to the location permissions per the documentation (https://pub.dev/packages/geolocator):

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

Regarding getting "intsantce of a Future" instead of the result you need to await the call to _determinePosition() just like this:

onPressed: () async{
            // PRINTING IN THE CONSOLE
           await _determinePosition();
          },

For using Geolocator as a service I recommend to use a dependency injection solution like Provider(https://pub.dev/packages/provider) or GetIt(https://pub.dev/packages/get_it)

Upvotes: 2

Jitesh Mohite
Jitesh Mohite

Reputation: 34270

Use below function which checks the permission and returns current position, so before getting location it's important to check whether we had required permission or not.

import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _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.deniedForever) {
      // Permissions are denied forever, handle appropriately. 
      return Future.error(
        'Location permissions are permanently denied, we cannot request permissions.');
    } 

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

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

Upvotes: 1

Related Questions