how to get current position from mapbox in Flutter - android

As i am using MapBox in my application .i don't know how to get the current position to open Navigation_MapBox for start navigation with the current position as origin to the destination .thanks

Use geolcator library
add it to pubspec yaml file
import it
import 'package:geolocator/geolocator.dart';
then
Position position = await Geolocator().getLastKnownPosition(desiredAccuracy: LocationAccuracy.high);
print("my location is ${position.latitude} ${position.longitude} ");

To get user location you need to run this
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.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.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}

Related

How do I add permission for Geolocator in Android?

So I have the following error:
√ Built build\app\outputs\flutter-apk\app-debug.apk.
D/FlutterLocationService( 6191): Creating service.
D/FlutterLocationService( 6191): Binding to location service.
Lost connection to device.
I also don't know why it says D/FlutterLocationService, instead of D/FlutterGeolocator.
I heard you now need to manually ask for permission, but have zero clue how to do that. How should I add the code for Geolocator permissions to this code?
AppStateProvider() {
_saveDeviceToken();
FirebaseMessaging.onMessage;
FirebaseMessaging.onMessageOpenedApp;
_setCustomMapPin();
_getUserLocation();
_listemToDrivers();
Geolocator.getPositionStream().listen(_updatePosition);
}
// ANCHOR: MAPS & LOCATION METHODS
_updatePosition(Position newPosition) {
position = newPosition;
notifyListeners();
}
Future<Position> _getUserLocation() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
position = await Geolocator.getCurrentPosition();
List<Placemark> placemark =
await placemarkFromCoordinates(position.latitude, position.longitude);
you simply add permission request before you get user location
so inside the _getUserLocation() and before
position = await Geolocator.getCurrentPosition();
add below code.
final 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.');
}
And you can probably check https://pub.dev/packages/geolocator as well

How to use Xamarin Android LocationManager.GetCurrentLocation?

How can you use LocationManager.GetCurrentLocation with Xamarin.Android?
Specifically, I can't figure out how to use the IConsumer parameter required.
Here's the documentation for it:
https://learn.microsoft.com/en-us/dotnet/api/android.locations.locationmanager.getcurrentlocation?view=xamarin-android-sdk-12
EDIT:
If I leave my test device (Android 6) on my desk, next to a window, it'll only ever return null locations until I walk around with the device. Network reception is good, and if I return to the exact same location once it's "woken up" then GPS signal is good. This is true even for the lowest accuracy request.
Here's an example of the code I'm using (have tried various timeouts, and polling continuously):
Here's the code I'm using:
// Get the last known location, from the OS cache
Location cached = await Geolocation.GetLastKnownLocationAsync();
// Location found?
if (cached != null)
OnLocationFound(cached);
// Get current location
GeolocationRequest networkRequest = new GeolocationRequest(GeolocationAccuracy.Lowest, timeout);
Location network = await Geolocation.GetLocationAsync(networkRequest, cancellationToken.Token);
// Location found?
if (network != null)
OnLocationFound(network);
// Get current location
GeolocationRequest gpsRequest = new GeolocationRequest(GeolocationAccuracy.Medium, timeout);
Location gps = await Geolocation.GetLocationAsync(gpsRequest, cancellationToken.Token);
// Location found?
if (gps != null)
OnLocationFound(gps);

I have tried eveything in my reach but didn't get the result. All i want to get the var lat and lon value from getLocation method

import 'package:geolocator/geolocator.dart';
class Location {
double ? lat;
double ? lon;
void getLocation() async {
Position position = await _determinePosition();
lat = position.latitude;
lon = position.longitude;
}
Future < Position > _determinePosition() async {
LocationPermission permission;
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Permission Denied');
}
}
return await Geolocator.getCurrentPosition();
}
}
As you can see the error, i can't even assign the value of lat and lon,and if i put null in there, it will show 0 in result. And i put late then,it waill show runtime error for initiatize the value before
Important thing is :
Add the permission in manifest .
Use permission handler and take permission from user.
After checking that we have permission, use the geolocator.
You have to await an async method, otherwise you don't lknow whether it's done yet. Since you managed to not return a Future<>, you cannot await your method. Matter of fact you didn't even try, otherwise you would have gotten a compiler error at that point.
Future<void> getLocation() async {
Position position = await _determinePosition();
lat = position.latitude;
lon = position.longitude;
}
Now you need to find where you call this method and then await it. Only then your values will be filled.

How to request permissions in a Flutter plugin?

I am trying to use a simple Flutter plugin (speech recognition wrapper) and have no idea how to request the appropriate permissions on Android 23 or newer. In the Dart part I have:
Future requestPermissions() =>
_channel.invokeMethod("speech.requestPermissions");
In the Android part:
public class SpeechRecognitionPlugin implements MethodCallHandler, RecognitionListener,
PluginRegistry.RequestPermissionResultListener {
Plugin registration:
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "speech_recognition");
SpeechRecognitionPlugin speechRecognitionPlugin = new
SpeechRecognitionPlugin(registrar.activity(), channel);
channel.setMethodCallHandler(speechRecognitionPlugin);
registrar.addRequestPermissionResultListener(speechRecognitionPlugin);
}
Method call:
else if (call.method.equals("speech.requestPermissions")) {
Log.d(LOG_TAG, "speech.requestPermissions");
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(activity.getApplicationContext(), "This application needs the Record Audio permission for recognition to work", Toast.LENGTH_LONG).show();
} else {
Log.d(LOG_TAG, "Requesting permissions");
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.RECORD_AUDIO},
1);
}
result.success(hasRecordAudioPermission());
Result callback:
#Override
public boolean onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
boolean granted = false;
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
granted = true;
}
speechChannel.invokeMethod("speech.onPermission", granted);
return true;
}
}
return false;
}
From logcat I see that the "speech.requestPermissions" call happens, but standard Android system permission request is not shown, just this in the logcat may be related:
D/ViewRootImpl(21171): #1 mView = android.widget.LinearLayout{64f050b
V.E...... ......I. 0,0-0,0 #102039d android:id/toast_layout_root}
D/ViewRootImpl(21171): MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl(21171): #3 mView = null
What is the correct way to request permissions for Flutter plugins?
EDIT: This does not apply to the first run, when the dialog shows correctly, but to subsequent runs when the user did not grant the permission at first or revoked it via settings. I realize that changes the question significantly (making it appear as edge case), but Android permissions are not supposed to work that way.
EDIT: The permissions are present in AndroidManifest.xml
Use Permission plugin for flutter
Request permission
import 'package:permissions_plugin/permissions_plugin.dart';
Map<Permission, PermissionState> permission = await PermissionsPlugin
.requestPermissions([
Permission.ACCESS_FINE_LOCATION,
Permission.ACCESS_COARSE_LOCATION,
Permission.READ_PHONE_STATE
]);
Check status permission
import 'package:permissions_plugin/permissions_plugin.dart';
Map<Permission, PermissionState> permission = await PermissionsPlugin
.checkPermissions([
Permission.ACCESS_FINE_LOCATION,
Permission.ACCESS_COARSE_LOCATION,
Permission.READ_PHONE_STATE
]);
I have this working for location permissions. The only thing I'm doing differently is in your method call here:
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.RECORD_AUDIO},
1);
Instead of using 'ActivityCompat' I store the registrar in a local final variable and I'm doing the following :
registrar.activity().requestPermissions(activity,
new String[]{Manifest.permission.RECORD_AUDIO},
1);
EDIT: Also make sure that you have included the relevant permissions in your AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Add this -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Flutter stuff --->
</manifest>
Let's say you want to request camera permission using permission_handler package.
In pubspec.yaml file:
permission_handler: ^8.0.0+2
(For Android) Add the permission to android/app/src/main/AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
(For iOS),
(i) Add this to your info.plist file
<key>NSCameraUsageDescription</key>
<string>App needs camera permission to work</string>
(ii) Add 'PERMISSION_CAMERA=1' to your Podfile.
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## Add the following line.
'PERMISSION_CAMERA=1'
]
end
end
end
Request the permission:
final status = await Permission.camera.request();
if (status == PermissionStatus.granted) {
print('Permission granted');
} else if (status == PermissionStatus.denied) {
print('Permission denied. Show a dialog and again ask for the permission');
} else if (status == PermissionStatus.permanentlyDenied) {
print('Take the user to the settings page.');
await openAppSettings();
}

un-nessesary permission check?

ello, i am trying to code the following function:
private int GetTwoLocationsAndDistance(Location location1, Location location2) {
if (location1 == null) {
location1 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location 2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
else {
location1 = location2;
location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
return int Distance;
}
(both location1 and location2 are initalized as null)
here, an error message comes up saying that a permission might need to happen.
but i already asked for permission onCreate(); with
eif (pm.checkPermission(permission.ACCESS_FINE_LOCATION, getPackageName()) == PackageManager.PERMISSION_DENIED) {
alertboxGPS();
}
(alertboxGPS is a box that pops up when permission is denied)
how do i fix this error?
The user can deny you the permission, that's why android studio suggests that you need to check if it's granted.
You can ensure that your app has the permission by adding this line in the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Or continue with the request/check permission method, however, let the user retry if the permission is not granted but is crucial.

Categories

Resources