我正在使用 api 创建一个天气应用程序
我创建了一个显示已保存城市天气的屏幕,这里有一个用于按城市名称或当前位置搜索城市的屏幕,
我想避免添加重复的城市...
我的代码工作正常,同时通过搜索城市作为给定的精确纬度和经度来添加,但在使用当前位置搜索时,它会有所不同 32.837373 32.837495
那么我如何避免当前位置重复,例如舍入数字或其他类型
以及纬度和经度的小数点后需要多少数字
这是我检查重复项的代码
bool isLocationExist(City city) {
bool flag = false;
for (var x in myCities) {
if (x.lat == city.lat && x.lon == city.lon) {
flag = true;
}
}
return flag;
}
void addCity(City city) {
if (!isLocationExist(city)) {
myCities.add(city);
myCities.refresh();
saveCityToStorage();
} else {
MyHelper.showSnackbar('Already Exist');
}
}
更改函数以舍入坐标。
roundCoordinate
:此函数将给定值(纬度或经度)四舍五入到指定的精度。
4 位小数可提供约 11 米的精度。
5 位小数可提供约 1.1 米的精度。
这是更新后的 Dart 代码:
bool isLocationExist(City city, {int precision = 4}) {
bool flag = false;
double roundedLat = roundCoordinate(city.lat, precision);
double roundedLon = roundCoordinate(city.lon, precision);
for (var x in myCities) {
double xRoundedLat = roundCoordinate(x.lat, precision);
double xRoundedLon = roundCoordinate(x.lon, precision);
if (xRoundedLat == roundedLat && xRoundedLon == roundedLon) {
flag = true;
break;
}
}
return flag;
}