Using geolocation to find the current position

There's a Flutter plugin called Geolocator that provides access to the platform-specific location services. Let's get started, as follows:

  1. We need to add the dependency in the pubspec.yaml file, like this:
  geolocator: ^5.3.0
  1. Then, in the main.dart file, we'll import the Geolocator library, as follows:
import 'package:geolocator/geolocator.dart';
  1. In order to find the current location of our user, we'll create a new method called _getCurrentLocation that will use the device GPS to find the latitude and longitude of the current location, and return it to the caller, as follows:
  Future _getCurrentLocation() async {}

Geolocator methods are all asynchronous, so our method will be asynchronous as well.

  1. Not all devices have the geolocation service available, so, inside the _getCurrentLocation method, we can check whether the functionality is available or not before finding the current position, by running the following code:
bool isGeolocationAvailable = await Geolocator().isLocationServiceEnabled(); 
  1. Then, if the service is available, we'll try to get the current position; otherwise, we'll return the previously set fixed position, as follows:
Position _position = Position(latitude: this.position.target.latitude, longitude: this.position.target.longitude);
if (isGeolocationAvailable) {
try {
_position = await Geolocator().getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
}
catch (error) {
return _position;
}
}
return _position;
The Geolocator().getCurrentPosition() method returns a Position object. This not only contains latitude and longitude, but can also contain other data—such as altitude, speed, and heading—that we don't need for this app but which might be useful to you for other apps.

Now that we have the current location of our user, let's see how to place a marker on that position on the map.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157