gpt4 book ai didi

flutter - 如何在 flutter 中获得经纬度

转载 作者:行者123 更新时间:2023-12-03 04:54:32 26 4
gpt4 key购买 nike

我可以弄清楚如何将用户的纬度和经度放在一起,但需要单独获取它们以利用 Geolocator 包中的 Geolocator().distanceBetween 函数。我下面的代码不断收到错误:

未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'latitude'。

接收方:空

尝试调用:纬度

  Future<Position> getLocation() async {
var currentLocation;
try {
currentLocation = await geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
} catch (e) {
currentLocation = null;
}
return currentLocation;
}


void calculateDistance() async {

getLocation().then((position) {
userLocation = position;
});

final double myPositionLat = userLocation.latitude;
final double myPositionLong = userLocation.longitude;

final double TPLat = 51.5148731;
final double TPLong = -0.1923663;
final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;

print(distanceInMetres);

}

最佳答案

试试这个 :

void calculateDistance() async {

getLocation().then((position) {
userLocation = position;


final double myPositionLat = userLocation.latitude;
final double myPositionLong = userLocation.longitude;

final double TPLat = 51.5148731;
final double TPLong = -0.1923663;
final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;

print(distanceInMetres);

});
}

或另一种方法是:
void calculateDistance() async {

userLocation = await getLocation();


final double myPositionLat = userLocation.latitude;
final double myPositionLong = userLocation.longitude;

final double TPLat = 51.5148731;
final double TPLong = -0.1923663;
final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;

print(distanceInMetres);
}

关于flutter - 如何在 flutter 中获得经纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com