user16867349
user16867349

Reputation:

how to get a user's location in flutter

I want to locate the user and send his location coordinates via api to the server, Please answer with code, I've tried library geolocator: ^7.7.0

void getCurrentLocation() async {
     Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
     var lat = position.latitude;
     var long = position.longitude;
 print("Latitude: $lat and Longitude: $long");
   }

This code is not working , Error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: MissingPluginException(No implementation found for method getCurrentPosition on channel flutter.baseflow.com/geolocator)
E/flutter (25476): #0      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:156
E/flutter (25476): <asynchronous suspension>
E/flutter (25476): #1      MethodChannelGeolocator.getCurrentPosition (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:128:27)
E/flutter (25476): <asynchronous suspension>
E/flutter (25476): #2      getCurrentLocation
package:check_time/Screens/fingerprint_Screen.dart:84
E/flutter (25476): <asynchronous suspension>

Upvotes: 2

Views: 5028

Answers (5)

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14835

Try below code hope its helpful to you, refer geolocator here and geocoding here for getting the latitude and longitude and your location name

Create Position and one variable for your current position and init() mathod

Position? _currentPosition;
  String? _currentAddress;
  void initState() {
    super.initState();
    getCurrentLocation();
  }

Function for get Latitude and Longitude

 getCurrentLocation() {
    Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.best,
            forceAndroidLocationManager: true)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
         print(position.latitude);
         print(position.longitude);
        _getAddressFromLatLng();
      });
    }).catchError((e) {
      print(e);
    });
  }

Function for location from your latitude and longitude

_getAddressFromLatLng() async {
    try {
      List<Placemark> placemarks = await placemarkFromCoordinates(
          _currentPosition!.latitude, _currentPosition!.longitude);

      Placemark place = placemarks[0];

      setState(() {
        _currentAddress = "${place.subLocality}";//here you can used place.country and other things also
        print(_currentAddress);
      });
    } catch (e) {
      print(e);
    }
  }

Your Widget:

Column(
      children: [
        if (_currentPosition != null && _currentAddress != null)
          Text(
            _currentAddress!,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              letterSpacing: .5,
              fontSize: 15,
              color: Colors.black,
            ),
          ),
      ],
    )

Add below lines inside android\app\src\main\AndroidManifest.xml file above of the application tag

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

Go to android\app\build.gradle file and change below changes

compileSdkVersion 31
minSdkVersion 21
targetSdkVersion 29

Upvotes: 0

Rutvik Moradiya
Rutvik Moradiya

Reputation: 88

There are some helpful steps to be followed by You which is mentioned on readme of package. Update

android\app\build.gradle

android {
  compileSdkVersion 31

  ...
}

Upvotes: 0

Vicky Salunkhe
Vicky Salunkhe

Reputation: 11005

This error usually occurs if you haven't made changes to the app as per the required app platform.

i.e, android, iOS, Web

GOTO the package in package description under Usage

follow the implementation steps for the platform you are building

enter image description here

Upvotes: 0

Rudrransh Saxena
Rudrransh Saxena

Reputation: 36

Build the app again. Try this code.

    Future<void> getCurrentLocation() async {
      Position position = await Geolocator.getCurrentPosition(
                           desiredAccuracy:LocationAccuracy.high);
      double lat = position.latitude;
      double long = position.longitude;
      print("Latitude: $lat and Longitude: $long");
  }

Upvotes: 1

Afzal
Afzal

Reputation: 419

Try restarting the application! should work from there onwards. Hot restart wont work when u add plugins.

Upvotes: 0

Related Questions