I have a google map used in my compose project. I meet some conflicts between keeping the CameraPositionState across navigation and avoiding crash.I only have two screens to navigate between btw. At first, I put the rememberCameraPositionState in the MapScreen as the docs suggested. It works fine. NO crash here. But when leaving the MapScreen, it lost its state. So did the cameraposition. It returned to the initial location when navigating back. I want it to keep the position as what Google Map and all other map apps do. So, I put the rememberCameraPositionState to the MainActivity.kt. That helps it to survive through navigation. Here is what happened. After that, the CameraPositionState did survive across navigtion. But the app crashed a lot. If I navigate to the other screen, and before that screen is solid, I click the navigation button to get back to MapScreen, the app crashed. Here is the error message.
java.lang.IllegalStateException: CameraPositionState may only be associated with one GoogleMap at a time
I am confused with this error.
How can I fix the problem. I want to keep the state and also no app crash.
Here is the structure of my project. If you need the source code, I'll upload it soon.
MainActivity.kt
class MainActivity : ComponentActivity() {
...
setContent(){
MayTrail()
}
}
MyTrail.kt this file only cotains navigation components
fun MyTrail() {
NavHost() {
...
}
}
MapScreen.kt
@Composable
fun MapScreen() {
GoogleMap()
}
HistoryScreen.kt
fun HistiryScreen() {
...
}
I have tried to test what went wrong and it all points to the rememberCameraPositionState. I saw the problem being repoted. And someone said it is fixed in a former version of maps-compose. But I encouter the problem in the latest version. So is it still a bug? Or I just used it in a wrong way.
CameraPositionState may only be associated with one GoogleMap at a time
You can control more different GoogleMap
with remember1 and remember2, remember3 etc.
Example:
val remember1 = rememberCameraPositionState()
val remember2 = rememberCameraPositionState()
val remember3 = rememberCameraPositionState()
....
GoogleMap(remember1)
GoogleMap(remember2)