android - 如何在喷气背包数据存储中保存收集的经纬度
问题描述
当我移动地图时,新坐标是从 MutableStateFlow 收集的。我想通过将地图移动到 DataStore 来保存新坐标,但它无法正常工作并且地图已损坏。我该如何解决?
在 ViewModel 代码中,我有这三个函数用于 INITIALS VALUES 和 UPDATE LOCATION VALUES 和 SET LOCATION
private val _location = MutableStateFlow(getInitialLocation())
val location: StateFlow<Location> = _location
private fun getInitialLocation(): Location = let {
Location("").let {
it.latitude = 14.599168243865952
it.longitude = 120.98413870283683
it
}
}
fun updateLocation(latitude: Double, longitude: Double) {
setLocation(Location("").let {
it.latitude = latitude
it.longitude = longitude
it
})
}
private fun setLocation(loc: Location) {
_location.value = loc
}
地图屏幕代码:
@Composable
private fun MapViewContainer(
mapView: MapView,
navigatorViewModel: PickLocationViewModel
) {
val context = LocalContext.current
val dataStore = CheckLocationIsSetDataStore(context = context)
AndroidView(
factory = { mapView }
) {
mapView.getMapAsync { map ->
map.apply {
navigatorViewModel.apply {
val location = location.value
val position = LatLng(location.latitude, location.longitude)
moveCamera(CameraUpdateFactory.newLatLngZoom(position, Constants.ZOOM_CAMERA))
setOnCameraIdleListener {
val cameraPosition = map.cameraPosition
updateLocation(
cameraPosition.target.latitude,
cameraPosition.target.longitude
)
}
viewModelScope.launch {
this@apply.location.collect{ location ->
dataStore.set(CheckLocationIsSetModel(location.altitude, location.longitude))
}
}
}
}
}
}
}
数据存储类代码:
class CheckLocationIsSetDataStore @Inject constructor(private val context: Context) :
IDataStore<CheckLocationIsSetModel, CheckLocationIsSetModel> {
override val get: Flow<CheckLocationIsSetModel>
get() = context.dataStore.data.catch { exception ->
if (exception is IOException) {
Log.e("DataStore Exception: ", exception.toString())
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
CheckLocationIsSetModel(
lat = preferences[DataStoreKeys.IS_LOCATION_LAT_SET_KEY]
?: Constants.IF_LOCATION_LAT_NOT_SET,
lng = preferences[DataStoreKeys.IS_LOCATION_LNG_SET_KEY]
?: Constants.IF_LOCATION_LNG_NOT_SET
)
}
override suspend fun set(param: CheckLocationIsSetModel?) {
context.dataStore.edit { preferences ->
preferences[DataStoreKeys.IS_LOCATION_LAT_SET_KEY] = param?.lat ?: 0.0
preferences[DataStoreKeys.IS_LOCATION_LNG_SET_KEY] = param?.lng ?: 0.0
}
}
}
解决方案
推荐阅读
- c++ - 我们可以在 cpp 中重命名 cout、endl 关键字吗?
- java - Azure函数java读取项目/资源中的文件?
- python - 合并pyspark数据框中的重复记录
- java - 如何分析Java中的多线程开销?
- uml - 在 UML 状态图中“做什么”是做什么的?
- java - 我有一个对象的 PriorityQueue,我需要根据浮点值对其进行排序。如何为它创建一个比较器?
- angularjs - 覆盖angularjs1.5中组件的templateurl
- javascript - 比较数组的索引元素
- python - Keras LSTM 输入和输出维度问题
- python - 未定义变量 'os' pylint(undefined-variable) [57,18]