目录
  • flutter 中获取地理位置
    • 先决条件
    • 使用 flutter 定位包
      • 设置
      • 位置权限
      • 获取当前位置
    • 使用 flutter 地理编码包
      • 设置
      • 获取地址
    • 常见的陷阱
      • 结论

      flutter 中获取地理位置

      如今,发现用户位置是移动应用程序非常常见且功能强大的用例。如果您曾经尝试过在 android 中实现位置,您就会知道样例代码会变得多么复杂和混乱。

      但这与 flutter 不同——它有很多令人惊叹的包,可以为您抽象出样板代码,并使实现地理定位成为梦想。另一个好的方面是您可以在 android 和 ios 上获得这些功能。

      让我们快速浏览一下我们今天正在构建的用于收集位置数据的内容:

      本文将带您了解两个最流行且易于使用的 flutter 地理定位包。

      让我们从location开始,这是flutter 最喜欢的包。这很简单。只需三个简单的步骤,您就可以获取当前用户位置以及处理位置权限。

      先决条件

      在继续前进之前,让我们快速检查一下我们需要的东西:

      • 该fluttersdk
      • 编辑器:您可以使用 visual code 或 android studio
      • 至少对 flutter 有初级的了解

      差不多就是这样!

      使用 flutter 定位包

      设置

      将依赖项添加到您的文件中:pubspec.yaml

          location: ^4.3.0

      由于 android 和 ios 处理权限的方式不同,因此我们必须在每个平台上分别添加它们。

      安卓版

      将以下位置权限添加到:androidmanifest.xml

      <uses-permission android:name="android.permission.access_coarse_location" /> 
      <uses-permission android:name="android.permission.access_fine_location" />

      如果您还想在后台访问用户的位置,请在访问后台位置之前使用该api,并在清单文件中添加后台权限:enablebackgroundmode({bool enable})

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

      对于 ios

      将以下位置权限添加到:info.plist

      <key>nslocationwheninuseusagedescription</key> 
      <string>此应用需要访问您的位置</string>

      nslocationwheninuseusagedescription是您需要的唯一许可。这也允许您访问后台位置,唯一需要注意的是,当应用程序在后台访问位置时,状态栏中会显示蓝色徽章。与 android 不同,我们在其中添加了单独的权限以在后台访问用户的位置。

      位置权限

      我们需要在请求用户位置之前检查位置服务状态和权限状态,这可以使用以下几行代码轻松完成:

      location location = new location();
      
      bool _serviceenabled;
      permissionstatus _permissiongranted;
      
      _serviceenabled = await location.serviceenabled();
      if (!_serviceenabled) {
       _serviceenabled = await location.requestservice();
       if (!_serviceenabled) {
         return null;
       }
      }
      
      _permissiongranted = await location.haspermission();
      if (_permissiongranted == permissionstatus.denied) {
       _permissiongranted = await location.requestpermission();
       if (_permissiongranted != permissionstatus.granted) {
         return null;
       }
      }

      首先,我们创建一个由location()包提供的对象,location反过来为我们提供了两个有用的方法。检查设备位置是否已启用或用户是否已手动禁用它。``serviceenabled()

      对于后者,我们显示了一个原生提示,允许用户通过调用快速启用位置,然后我们再检查一次,如果他们从提示中启用了它。requestservice()

      一旦我们确定启用了位置服务,下一步就是通过调用它来检查我们的应用程序是否具有使用它的必要权限,这将返回.haspermission()``permissionstatus

      permissionstatus是可以具有以下三个值之一的枚举:

      • permissionstatus.granted: 定位服务权限已被授予
      • permissionstatus.denied: 定位服务权限被拒绝
      • permissionstatus.deniedforever: 位置服务权限被用户永久拒绝。这仅适用于 ios。在这种情况下不会显示对话框requestpermission()

      如果状态为 ,我们可以通过调用显示请求位置权限的系统提示。对于 status,我们可以立即访问 location,因此我们返回一个.denied,``requestpermission()``granted``null

      如果您还想在后台访问用户位置,请使用。location.enablebackgroundmode(enable: **true**)

      获取当前位置

      如果位置服务可用并且用户已授予位置权限,那么我们只需两行代码即可获取用户位置 – 不,我不是在开玩笑:

      locationdata _locationdata;
      _locationdata = await location.getlocation();

      locationdata类提供以下位置信息:

      class locationdata {
        final double latitude; // latitude, in degrees
        final double longitude; // longitude, in degrees
        final double accuracy; // estimated horizontal accuracy of this location, radial, in meters
        final double altitude; // in meters above the wgs 84 reference ellipsoid
        final double speed; // in meters/second
        final double speedaccuracy; // in meters/second, always 0 on ios
        final double heading; // heading is the horizontal direction of travel of this device, in degrees
        final double time; // timestamp of the locationdata
        final bool ismock; // is the location currently mocked
      }

      您还可以通过添加onlocationchanged侦听器在用户位置发生变化时监听位置更新来获得连续回调,这是出租车应用程序、司机/骑手应用程序等的一个很好的用例:

      location.onlocationchanged.listen((locationdata currentlocation) {
        // current user location
      });

      注意,一旦您想停止收听更新,请不要忘记取消流订阅。

      瞧!现在我们有了用户位置的当前纬度和经度值。

      让我们利用这些纬度和经度值来获取用户的完整地址或反向地理编码。

      为此,我们将使用另一个惊人的 flutter 包:geocode。

      使用 flutter 地理编码包

      设置

      将依赖项添加到您的文件中:pubspec.yaml

      dependencies:
          geocode: 1.0.1

      获取地址

      获取地址再简单不过了。就打电话吧。就是这样!带有空检查的完整函数如下所示:reversegeocoding(latitude: lat, longitude: lang)

      future<string> _getaddress(double? lat, double? lang) async {
       if (lat == null || lang == null) return "";
       geocode geocode = geocode();
       address address =
           await geocode.reversegeocoding(latitude: lat, longitude: lang);
       return "${address.streetaddress}, ${address.city}, ${address.countryname}, ${address.postal}";
      }
      

      没那么简单!

      完整的代码如下所示:

      class getuserlocation extends statefulwidget {
       getuserlocation({key? key, required this.title}) : super(key: key);
       final string title;
      
       @override
       _getuserlocationstate createstate() => _getuserlocationstate();
      }
      
      class _getuserlocationstate extends state<getuserlocation> {
       locationdata? currentlocation;
       string address = "";
      
       @override
       widget build(buildcontext context) {
         return scaffold(
           appbar: appbar(),
           body: center(
             child: padding(
               padding: edgeinsets.all(16.0),
               child: column(
                 mainaxisalignment: mainaxisalignment.center,
                 children: <widget>[
                   if (currentlocation != null)
                     text(
                         "location: ${currentlocation?.latitude}, ${currentlocation?.longitude}"),
                   if (currentlocation != null) text("address: $address"),
                   materialbutton(
                     onpressed: () {
                       _getlocation().then((value) {
                         locationdata? location = value;
                         _getaddress(location?.latitude, location?.longitude)
                             .then((value) {
                           setstate(() {
                             currentlocation = location;
                             address = value;
                           });
                         });
                       });
                     },
                     color: colors.purple,
                     child: text(
                       "get location",
                       style: textstyle(color: colors.white),
                     ),
                   ),
                 ],
               ),
             ),
           ),
         );
       }
      
       future<locationdata?> _getlocation() async {
         location location = new location();
         locationdata _locationdata;
      
         bool _serviceenabled;
         permissionstatus _permissiongranted;
      
         _serviceenabled = await location.serviceenabled();
         if (!_serviceenabled) {
           _serviceenabled = await location.requestservice();
           if (!_serviceenabled) {
             return null;
           }
         }
      
         _permissiongranted = await location.haspermission();
         if (_permissiongranted == permissionstatus.denied) {
           _permissiongranted = await location.requestpermission();
           if (_permissiongranted != permissionstatus.granted) {
             return null;
           }
         }
      
      
         _locationdata = await location.getlocation();
      
         return _locationdata;
       }
      
       future<string> _getaddress(double? lat, double? lang) async {
         if (lat == null || lang == null) return "";
         geocode geocode = geocode();
         address address =
             await geocode.reversegeocoding(latitude: lat, longitude: lang);
         return "${address.streetaddress}, ${address.city}, ${address.countryname}, ${address.postal}";
       }
      }

      常见的陷阱

      尽管这些软件包让我们的生活变得更轻松,而且我们不必处理在 android 和 ios 中本地访问位置的复杂过程,但您可能会面临很多问题。让我们来看看它们以及可以帮助您修复这些问题的步骤:

      • 应用内存泄漏:如果您一直在收听位置更新,请确保取消流订阅,一旦您想停止收听更新
      • 用户必须接受位置权限才能始终允许使用后台位置。位置权限对话框提示中未显示始终允许的 android 11 选项。用户必须从应用程序设置中手动启用它
      • 用户可能在 ios 上永远拒绝定位,因此不会显示要求定位权限的本机提示。确保处理这种边缘情况requestpermisssions()
      • 用户可能随时从应用程序设置中撤销位置权限,因此在访问位置数据之前,请确保在应用程序恢复时检查它们

      结论

      由于 flutter 简化了访问位置,因此我们作为开发人员可能会立即将其添加到我们的应用程序中。但同时,我们需要确保我们的应用程序真正适合请求用户位置并利用它为用户增加一些价值的用例,而不是仅仅将位置数据发送到服务器。

      随着即将推出的 android 和 ios 操作系统版本中安全性和隐私性的提高,访问位置数据而不向用户提供价值可能会导致您的应用程序被商店拒绝。有很多很好的用例,您可以使用用户位置,例如,根据用户位置为食品/外卖应用程序个性化主屏幕,该应用程序显示按用户当前位置的接近程度订购的餐厅。取件/送货应用程序是最常见的用例。

      您还可以在您实际想要使用的特定屏幕上询问用户位置,而不是立即在主屏幕上询问。这使用户更清楚,并且他们不太可能拒绝位置权限。

      到此这篇关于使用flutter定位包获取地理位置的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。