简体   繁体   English

颤振地理定位器包不返回经度和纬度值

[英]flutter geolocator package not returning the longitude and latitude values

I am using the flutter geolocator package to get a device's current location.我正在使用颤振地理定位器包来获取设备的当前位置。 but, it is not returning the location and sends null values instead of longitude and latitude.但是,它不返回位置并发送空值而不是经度和纬度。

I have linked all the codes related to location access for Android and iOS.我已经链接了与 Android 和 iOS 的位置访问相关的所有代码。

Here is my code这是我的代码

loading_screen.dart loading_screen.dart

import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';

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

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();
    print('init state called');
    getLocation();
  }

  double? lat;
  double? long;

  void getLocation() async {
    Location location = Location();
    await location.getCurrentLocation();
    print(location.longitude);
    print(location.latitude);
    lat = location.latitude;
    long = location.longitude;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('$lat & $long'),
      ),
    );
  }
}

location.dart位置.dart

import 'package:geolocator/geolocator.dart';

class Location {
  double? longitude;
  double? latitude;

  Future<void> getCurrentLocation() async {
    try {
      Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.lowest);
      longitude = position.longitude;
      latitude = position.latitude;
    } catch (e) {
      print(e);
    }
  }
}

Here is the console log这是控制台日志

Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
D/FlutterGeolocator( 9601): Attaching Geolocator to activity
D/FlutterGeolocator( 9601): Creating service.
D/FlutterGeolocator( 9601): Binding to location service.
D/FlutterGeolocator( 9601): Geolocator foreground service connected
D/FlutterGeolocator( 9601): Initializing Geolocator services
Debug service listening on ws://127.0.0.1:52220/Dm4z5g8IYT4=/ws
Syncing files to device SM A528B...
I/flutter ( 9601): init state called
I/BufferQueueProducer( 9601): [SurfaceView - com.kanuthakor.clima/com.kanuthakor.clima.MainActivity@e98a93d@0#1(BLAST Consumer)1](id:258100000001,api:1,p:9601,c:9601) queueBuffer: queued for the first time.
D/ViewRootImpl@797d88a[MainActivity]( 9601): Creating frameDrawingCallback nextDrawUseBlastSync=false reportNextDraw=true hasBlurUpdates=false
D/ViewRootImpl@797d88a[MainActivity]( 9601): Creating frameCompleteCallback
I/SurfaceView@e98a93d( 9601): uSP: rtp = Rect(0, 0 - 1080, 2265) rtsw = 1080 rtsh = 2265
I/SurfaceView@e98a93d( 9601): onSSPAndSRT: pl = 0 pt = 0 sx = 1.0 sy = 1.0
I/SurfaceView@e98a93d( 9601): aOrMT: uB = true t = android.view.SurfaceControl$Transaction@10aa451 fN = 1 android.view.SurfaceView.access$500:124 android.view.SurfaceView$SurfaceViewPositionUpdateListener.positionChanged:1728 android.graphics.RenderNode$CompositePositionUpdateListener.positionChanged:319 
I/SurfaceView@e98a93d( 9601): aOrMT: vR.mWNT, vR = ViewRootImpl@797d88a[MainActivity]
I/ViewRootImpl@797d88a[MainActivity]( 9601): mWNT: t = android.view.SurfaceControl$Transaction@10aa451 fN = 1 android.view.SurfaceView.applyOrMergeTransaction:1628 android.view.SurfaceView.access$500:124 android.view.SurfaceView$SurfaceViewPositionUpdateListener.positionChanged:1728 
I/ViewRootImpl@797d88a[MainActivity]( 9601): mWNT: merge t to BBQ
D/ViewRootImpl@797d88a[MainActivity]( 9601): Received frameDrawingCallback frameNum=1. Creating transactionCompleteCallback=false
I/BufferQueueProducer( 9601): [ViewRootImpl@797d88a[MainActivity]#0(BLAST Consumer)0](id:258100000000,api:1,p:9601,c:9601) queueBuffer: queued for the first time.
D/OpenGLRenderer( 9601): GPIS:: SetUp Pid : 9601    Tid : 9632
D/ViewRootImpl@797d88a[MainActivity]( 9601): Received frameCompleteCallback  lastAcquiredFrameNum=1 lastAttemptedDrawFrameNum=1
I/ViewRootImpl@797d88a[MainActivity]( 9601): [DP] pdf(0) 1 android.view.ViewRootImpl.lambda$addFrameCompleteCallbackIfNeeded$3$ViewRootImpl:4987 android.view.ViewRootImpl$$ExternalSyntheticLambda16.run:6 android.os.Handler.handleCallback:938 
I/ViewRootImpl@797d88a[MainActivity]( 9601): [DP] rdf()
D/ViewRootImpl@797d88a[MainActivity]( 9601): reportDrawFinished (fn: -1) 
I/ViewRootImpl@797d88a[MainActivity]( 9601): MSG_WINDOW_FOCUS_CHANGED 1 1
D/InputMethodManager( 9601): startInputInner - Id : 0
I/InputMethodManager( 9601): startInputInner - mService.startInputOrWindowGainedFocus
D/InputMethodManager( 9601): startInputInner - Id : 0

any help will be highly appreciated, thank you.任何帮助将不胜感激,谢谢。

The problem is most likely the use of LocationAccuracy.lowest .问题很可能是使用LocationAccuracy.lowest On Android this translates to the PASSIVE_INTERVAL setting.在 Android 上,这转换为PASSIVE_INTERVAL设置。 This means that the location request will not trigger the location services to fetch a location but instead only return location triggered by other clients actively requesting a location update.这意味着位置请求不会触发位置服务获取位置,而只会返回由其他主动请求位置更新的客户端触发的位置。

You'd most likely want to update the accuracy to LocationAccuracy.low or higher if you want to actively trigger a location update and not rely on other applications to acquire a location for you.如果您想主动触发位置更新并且不依赖其他应用程序为您获取位置,您很可能希望将准确度更新为LocationAccuracy.low或更高。

Here is a complete overview of all accuracy options and their Android counterparts:以下是所有准确度选项及其 Android 对应项的完整概述:

Geolocator地理定位器 Android安卓
LocationAccuracy.lowest LocationAccuracy.lowest PRIORITY_PASSIVE PRIORITY_PASSIVE
LocationAccuracy.low LocationAccuracy.low PRIORITY_LOW_POWER PRIORITY_LOW_POWER
LocationAccuracy.medium LocationAccuracy.medium PRIORITY_BALANCED_POWER_ACCURACY PRIORITY_BALANCED_POWER_ACCURACY
LocationAccuracy.high LocationAccuracy.high PRIORITY_HIGH_ACCURACY PRIORITY_HIGH_ACCURACY
LocationAccuracy.best LocationAccuracy.best PRIORITY_HIGH_ACCURACY PRIORITY_HIGH_ACCURACY
LocationAccuracy.bestForNavigation LocationAccuracy.bestForNavigation PRIORITY_HIGH_ACCURACY PRIORITY_HIGH_ACCURACY

Did you given these permissions?您是否授予了这些权限?

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

You need to check run time permission and I didn't use your Location class.您需要检查运行时权限,而我没有使用您的 Location 类。


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

//import 'package:clima/services/location.dart';

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

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();
    print('init state called');
    getLocation();
  }

  double? lat;
  double? long;

  Future<Position> getLocation() async {
    Location location = Location();

    bool serviceEnabled;
    LocationPermission permission;
    print('inside getLoction1');

    // 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.
      print('Location services are disabled.');
    }
    print('inside getLoction2');

    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.
        print('Location permissions are denied');
      }
      print('inside getLoction3');
    }
    print('inside getLoction4');
    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      print(
          'Location permissions are permanently denied, we cannot request permissions.');
    }
    print('inside getLoction5');
    final position = await Geolocator.getCurrentPosition();

    print(position.latitude);

    print(location.longitude);
    print(location.latitude);
    print('inside getLoctio6');
    lat = location.latitude;
    long = location.longitude;
    return position;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<Position>(
          future: getLocation(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            if (snapshot.connectionState == ConnectionState.done) {
              print(snapshot.data!.latitude);
              return Center(
                child: Text(
                    '${snapshot.data!.latitude}${snapshot.data!.longitude}'),
              );
            } else {
              return SizedBox.shrink();
            }
          }),
    );
  }
}

I added an enquiry like yours today, I didn't see yours earlier, but yes, I have found that only null values are being given by geolocator 8.2.1 when position data is requested by Flutter.我今天添加了一个像您这样的查询,我之前没有看到您的查询,但是是的,我发现当 Flutter 请求位置数据时,geolocator 8.2.1 只给出空值。 You might be using a real device, viewing your console response.您可能正在使用真实设备,查看控制台响应。 I have been using the Android Emulator ... I checked, and the location services are enabled, the permission for position data to be noticed is given, and then despite these the position data given is null for long/lat ... I even entered settings to add a location to the emulator, but it made no difference ...我一直在使用 Android Emulator ...我检查了,并且启用了位置服务,给出了要注意位置数据的权限,然后尽管这些给出的位置数据对于 long/lat 是 null ...我什至输入设置以向模拟器添加位置,但没有任何区别......

My Code, Dart:我的代码,飞镖:

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

void main() {
  runApp(ScreenView());
}

class ScreenView extends StatefulWidget {
  double? latitude;
  double? longitude;

  ScreenView({this.latitude, this.longitude});

  void locationHereIs() async {
    await locationServicesStatus();
    await checkLocationPermissions();
    try {
      Position position = await Geolocator.getCurrentPosition(
              desiredAccuracy: LocationAccuracy.low)
          .timeout(Duration(seconds: 28));
      print(position);
    } catch (e) {
      print(e);
    }
  }

  Future<void> checkLocationPermissions() async {
    LocationPermission permission = await Geolocator.requestPermission();
    print('Current Location Permission Status = $permission.');
  }

  void checkLocationSettings() async {
    await Geolocator.openLocationSettings();
  }

  Future<void> locationServicesStatus() async {
    bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();
    print(
        'Currently, the emulator\'s Location Services Status = $isLocationServiceEnabled.');
  }

  @override
  State<ScreenView> createState() => _ScreenViewState();
}

class _ScreenViewState extends State<ScreenView> {
  @override
  void initState() {
    ScreenView().locationHereIs();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

If anyone has an idea on what could be improved for position data to be received, please respond to my problem also ... I'm in the same boat as Kanu ... Thank you : )如果有人对接收位置数据有什么可以改进的想法,请也回答我的问题......我和卡努在同一条船上......谢谢:)

I have found a solution and a reasonable explanation for why current-position data will not be retrieved by geolocator when operating with我已经找到了一个解决方案和一个合理的解释,解释为什么在使用地理定位器时不会检索当前位置数据

  • android's emulator安卓模拟器

:

The reason is because the android emulator is not a real device and lacks the level of functionality found within real android devices;原因是 android 模拟器不是真正的设备,缺乏真正的 android 设备中的功能级别; android emulator does not support geolocator's current-position function. android 模拟器不支持地理定位器的当前位置功能。

Android emulator does support geolocator's lastKnownLocation function though, and a location set within the emulator's location settings will be noticed and confirmed by geolocator via its lastKnownLocation function. Android 模拟器确实支持 geolocator 的lastKnownLocation函数,并且在模拟器的位置设置中设置的位置将被 geolocator 通过其 lastKnownLocation 函数注意到和确认。

I trust that this finding helps everyone working with geolocator relying on the android emulator : )我相信这个发现可以帮助每个依赖android 模拟器使用geolocator的人:)

Dart code example:飞镖代码示例:

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

void main() {
  runApp(ScreenView());
}

class ScreenView extends StatefulWidget {
  double? latitude;
  double? longitude;

  ScreenView({this.latitude, this.longitude});

  void lastKnownPosition() async {
    await locationServicesStatus();
    await checkLocationPermissions();
    try {
      Position? position = await Geolocator.getLastKnownPosition();
      print(position);
    } catch (e) {
      print(e);
    }
  }

  void locationHereIs() async {
    await locationServicesStatus();
    await checkLocationPermissions();
    try {
      Position position = await Geolocator.getCurrentPosition(
              desiredAccuracy: LocationAccuracy.low)
          .timeout(Duration(seconds: 28));
      print(position);
    } catch (e) {
      print(e);
    }
  }

  Future<void> checkLocationPermissions() async {
    LocationPermission permission = await Geolocator.requestPermission();
    print('Current Location Permission Status = $permission.');
  }

  void checkLocationSettings() async {
    await Geolocator.openLocationSettings();
  }

  Future<void> locationServicesStatus() async {
    bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();
    print(
        'Currently, the emulator\'s Location Services Status = $isLocationServiceEnabled.');
  }

  @override
  State<ScreenView> createState() => _ScreenViewState();
}

class _ScreenViewState extends State<ScreenView> {
  @override
  void initState() {
    ScreenView().lastKnownPosition();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Console output with lastKnownLocation :带有lastKnownLocation的控制台输出:

✓  Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
Debug service listening on ws://127.0.0.1:52586/aA04hHZ7dIg=/ws
Syncing files to device sdk gphone64 x86 64...
I/flutter (11353): Currently, the emulator's Location Services Status = true.
D/CompatibilityChangeReporter(11353): Compat change id reported: 78294732; UID 10149; state: ENABLED
I/flutter (11353): Current Location Permission Status = LocationPermission.whileInUse.
I/flutter (11353): Latitude: 37.333333333333336, Longitude: -121.89206891099967

Conclusion: there has been a suspicion that the geolocator package is flawed without explanation.结论:有人怀疑地理定位器包有缺陷,没有解释。 The above shows and explains that geolocator works fine with android emulator and should remain a favourite of developers.上面显示并解释了 geolocator 在 android 模拟器上工作得很好,应该仍然是开发人员的最爱。

I had same issue with geolocator but when I added <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> permission along with ACCESS_COARSE_LOCATION in manifest, and most importantly, I changed the accuracy to LocationAccuracy.high .我对地理定位器有同样的问题,但是当我在清单中添加<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />权限以及ACCESS_COARSE_LOCATION时,最重要的是,我将精度更改为LocationAccuracy.high After this, everything worked perfectly.在此之后,一切都很完美。

Here is my code.这是我的代码。

In manifest在清单中

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

In dart side.在飞镖方面。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter 的地理定位器 package 返回纬度和经度值的空值。 为什么? [安卓] - Flutter's Geolocator package returns nulls for latitude and longitude values. Why? [Android] Flutter 如何使用地理定位器 package 获取纬度、经度? - Flutter how to get latitude, longitude using geolocator package? 使用“GeoLocator”package 时无法获取纬度和经度 - Not able to get the Latitude and Longitude while using 'GeoLocator' package Geolocator 包不起作用,Flutter - Geolocator package is not working, Flutter Flutter 地理定位器 package 在 IOS 应用程序上给出负纬度,在 ZE84E30B9390CDB46DZDB687 上给出正确坐标 - Flutter geolocator package is giving negative latitude on IOS app and correct coordinates on Android Flutter 地理定位器不返回任何结果 - Flutter Geolocator Not returning any result Flutter 地理定位器 package 未检索位置 - Flutter geolocator package not retrieving location Flutter - Geolocator 包没有多次调用 Geolocator.getCurrentPosition() - Flutter - Geolocator package is not calling Geolocator.getCurrentPosition() more than once 如何在颤振中获得纬度和经度 - How to get latitude and longitude in flutter Flutter 获取位置和经纬度 - Flutter fetch Location and Latitude and Longitude
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM