我想定位用户并通过api将他的位置坐标发送到服务器,请用代码回答,我已经尝试过库地理定位器:^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");
}
此代码不起作用,错误:
[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>
再次构建应用程序。试试这个代码。
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");
}
尝试重新启动应用程序!应该从那里开始工作。当你添加插件时热重启将不起作用。
您需要遵循一些有用的步骤,这些步骤在软件包的自述文件中提到。更新
android\app\build.gradle
android {
compileSdkVersion 31
...
}
尝试下面的代码希望对您有帮助,请参考
geolocator
这里和geocoding
这里获取纬度和经度以及您的位置名称
为您当前的位置创建位置和一个变量以及
init()
方法
Position? _currentPosition;
String? _currentAddress;
void initState() {
super.initState();
getCurrentLocation();
}
获取经纬度函数
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);
});
}
根据您的纬度和经度定位的函数
_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);
}
}
您的小部件:
Column(
children: [
if (_currentPosition != null && _currentAddress != null)
Text(
_currentAddress!,
style: TextStyle(
fontWeight: FontWeight.bold,
letterSpacing: .5,
fontSize: 15,
color: Colors.black,
),
),
],
)
在
android\app\src\main\AndroidManifest.xml
标签上方的 application
文件中添加以下行
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
转到android\app\build.gradle
文件并更改以下更改
compileSdkVersion 31
minSdkVersion 21
targetSdkVersion 29