在QuerySnapshot Flatter Firebase always null中使用ForEach是否有问题
我有以下返回未来列表的代码。我遍历每个文档,获取其纬度和经度,然后计算项目lat/long与当前位置或任何其他位置之间的距离。两个主要问题:在QuerySnapshot Flatter Firebase always null中使用ForEach是否有问题,firebase,flutter,google-cloud-firestore,location,Firebase,Flutter,Google Cloud Firestore,Location,我有以下返回未来列表的代码。我遍历每个文档,获取其纬度和经度,然后计算项目lat/long与当前位置或任何其他位置之间的距离。两个主要问题: 即使数据不为null,itemAddressLat和itemAddressLong也会抛出null,但如果我将这两个求值替换为: itemAddressLat = double.tryParse(doc.data()[Str.ITEM_LATITUDE].toString()) ?? 0.00
itemAddressLat =
double.tryParse(doc.data()[Str.ITEM_LATITUDE].toString()) ??
0.00;
itemAddressLong = double.tryParse(
doc.data()[Str.ITEM_LONGITUDE].toString()) ??
0.00;
Future<List> getDistances() async {
double itemAddressLat = 0.0;
double itemAddressLong = 0.0;
await FirebaseFirestore.instance
.collection(Str.ITEMS)
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {//DEBUGGING THIS IT WILL SHOW THE CORRECT LATITUDE AND LONGITUDE AS BUT THE DISTANCE IS NOT CORRECT:
itemAddressLat =
double.tryParse(doc.data()[Str.ITEM_LATITUDE].toString());
itemAddressLong =
double.tryParse(doc.data()[Str.ITEM_LONGITUDE].toString());
distance = distanceBetween(itemAddressLat, itemAddressLong,
usersCurrentLocationLat, usersCurrentLocationLong);
//breakpoint at this point will first show distance as null while the coordinates as: -1.2675001, 22.7865, 0.3367397, 32.6650065 (I copied this from the debugger) and pressing continue once, then the distance is: 1114005.0 pressing continue second time, distance is now: 3603715.0 increasing. This is not setting properly - expected: each loop the distance for the once cycle is set.
distance = distance.roundToDouble();
distanceList.add(distance);
})
});
return distanceList;
}
void testDistanceBetween() {THIS WORKS
double distanceInMeters =
distanceBetween(-1.2675001, 22.7865, 0.3466796, 32.6590033); returns: 1113
print("TO BE SURE IF THIS WORKS: " + (distanceInMeters / 1000).toString());
}
我使用了下面的另一种方法来计算距离,结果是相同的=distanceBetween不是问题,问题是foreach循环,即guese
另一种距离计算器方法由@提供:
好几天了,我的头都裂了
double distanceInMeters = distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);
double calculateDistance(double lat1, double lng1, double lat2, double lng2) {
double radEarth = 6.3781 * (pow(10.0, 6.0));
double phi1 = lat1 * (pi / 180);
double phi2 = lat2 * (pi / 180);
double delta1 = (lat2 - lat1) * (pi / 180);
double delta2 = (lng2 - lng1) * (pi / 180);
double cal1 = sin(delta1 / 2) * sin(delta1 / 2) +
(cos(phi1) * cos(phi2) * sin(delta2 / 2) * sin(delta2 / 2));
double cal2 = 2 * atan2((sqrt(cal1)), (sqrt(1 - cal1)));
double distance = radEarth * cal2;
return (distance);
}