如何在颤振中获取用户的位置 [英] how to get a user's location in flutter

查看:26
本文介绍了如何在颤振中获取用户的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定位用户并通过api将他的位置坐标发送到服务器,请用代码回答,我试过图书馆地理定位器:^7.7.0

void getCurrentLocation() async {Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);var lat = position.latitude;var long = position.longitude;打印(纬度:$lat 和经度:$long");}

此代码无效,错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] 未处理的异常:MissingPluginException(在频道 flutter.baseflow.com/geolocator 上找不到方法 getCurrentPosition 的实现)E/flutter (25476):#0 MethodChannel._invokeMethod包:flutter/…/services/platform_channel.dart:156E/flutter (25476):<异步悬挂>E/flutter (25476): #1 MethodChannelGeolocator.getCurrentPosition (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:128:27)E/flutter (25476):<异步悬挂>E/flutter (25476):#2 getCurrentLocation包:check_time/Screens/fingerprint_Screen.dart:84E/flutter (25476):<异步悬挂>

解决方案

试试下面的代码希望对你有帮助,参考 geolocator 此处 和地理编码 此处 用于获取经纬度和您的位置名称>

为当前位置创建位置和一个变量以及init() mathod

位置?_当前位置;细绳?_目前的地址;无效的初始化状态(){super.initState();获取当前位置();}

获取纬度和经度的函数

 getCurrentLocation() {Geolocator.getCurrentPosition(requiredAccuracy: LocationAccuracy.best,forceAndroidLocationManager: 真).then((位置位置){设置状态((){_currentPosition = 位置;打印(位置.纬度);打印(位置.经度);_getAddressFromLatLng();});}).catchError((e) {打印(e);});}

根据您的经纬度定位功能

_getAddressFromLatLng() 异步 {尝试 {列表<地标>地标 = 等待地标从坐标(_currentPosition!.latitude, _currentPosition!.longitude);地标位置 = 地标[0];设置状态((){_currentAddress = "${place.subLocality}";//这里也可以使用place.country等打印(_当前地址);});}赶上(e){打印(e);}}

您的小部件:

列(孩子们: [if (_currentPosition != null && _currentAddress != null)文本(_目前的地址!,样式:文本样式(fontWeight: FontWeight.bold,字母间距:.5,字体大小:15,颜色:Colors.black,),),],)

application 标签上方的 android\app\src\main\AndroidManifest.xml 文件中添加以下几行

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

转到 android\app\build.gradle 文件并更改以下更改

compileSdkVersion 31minSdk 版本 21目标SDK版本29

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>

解决方案

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

这篇关于如何在颤振中获取用户的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆