-
Notifications
You must be signed in to change notification settings - Fork 129
/
GoogleMap.kt
211 lines (195 loc) · 8.66 KB
/
GoogleMap.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.maps.android.compose
import android.content.ComponentCallbacks
import android.content.res.Configuration
import android.location.Location
import android.os.Bundle
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Composition
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCompositionContext
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.google.android.gms.maps.GoogleMapOptions
import com.google.android.gms.maps.LocationSource
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.PointOfInterest
import com.google.maps.android.ktx.awaitMap
import kotlinx.coroutines.awaitCancellation
/**
* A compose container for a [MapView].
*
* @param modifier Modifier to be applied to the GoogleMap
* @param cameraPositionState the [CameraPositionState] to be used to control or observe the map's
* camera state
* @param contentDescription the content description for the map used by accessibility services to
* describe the map. If none is specified, the default is "Google Map".
* @param googleMapOptionsFactory the block for creating the [GoogleMapOptions] provided when the
* map is created
* @param properties the properties for the map
* @param locationSource the [LocationSource] to be used to provide location data
* @param uiSettings the [MapUiSettings] to be used for UI-specific settings on the map
* @param indoorStateChangeListener listener for indoor building state changes
* @param onMapClick lambda invoked when the map is clicked
* @param onMapLoaded lambda invoked when the map is finished loading
* @param onMyLocationButtonClick lambda invoked when the my location button is clicked
* @param onMyLocationClick lambda invoked when the my location dot is clicked
* @param onPOIClick lambda invoked when a POI is clicked
* @param contentPadding the padding values used to signal that portions of the map around the edges
* may be obscured. The map will move the Google logo, etc. to avoid overlapping the padding.
* @param content the content of the map
*/
@Composable
public fun GoogleMap(
modifier: Modifier = Modifier,
cameraPositionState: CameraPositionState = rememberCameraPositionState(),
contentDescription: String? = null,
googleMapOptionsFactory: () -> GoogleMapOptions = { GoogleMapOptions() },
properties: MapProperties = DefaultMapProperties,
locationSource: LocationSource? = null,
uiSettings: MapUiSettings = DefaultMapUiSettings,
indoorStateChangeListener: IndoorStateChangeListener = DefaultIndoorStateChangeListener,
onMapClick: (LatLng) -> Unit = {},
onMapLongClick: (LatLng) -> Unit = {},
onMapLoaded: () -> Unit = {},
onMyLocationButtonClick: () -> Boolean = { false },
onMyLocationClick: (Location) -> Unit = {},
onPOIClick: (PointOfInterest) -> Unit = {},
contentPadding: PaddingValues = NoPadding,
content: (@Composable @GoogleMapComposable () -> Unit)? = null,
) {
// Early return if in preview
if (LocalInspectionMode.current) {
return
}
val context = LocalContext.current
val mapView = remember { MapView(context, googleMapOptionsFactory()) }
AndroidView(modifier = modifier, factory = { mapView })
MapLifecycle(mapView)
// rememberUpdatedState and friends are used here to make these values observable to
// the subcomposition without providing a new content function each recomposition
val mapClickListeners = remember { MapClickListeners() }.also {
it.indoorStateChangeListener = indoorStateChangeListener
it.onMapClick = onMapClick
it.onMapLongClick = onMapLongClick
it.onMapLoaded = onMapLoaded
it.onMyLocationButtonClick = onMyLocationButtonClick
it.onMyLocationClick = onMyLocationClick
it.onPOIClick = onPOIClick
}
val currentLocationSource by rememberUpdatedState(locationSource)
val currentCameraPositionState by rememberUpdatedState(cameraPositionState)
val currentContentPadding by rememberUpdatedState(contentPadding)
val currentUiSettings by rememberUpdatedState(uiSettings)
val currentMapProperties by rememberUpdatedState(properties)
val parentComposition = rememberCompositionContext()
val currentContent by rememberUpdatedState(content)
LaunchedEffect(Unit) {
disposingComposition {
mapView.newComposition(parentComposition) {
MapUpdater(
contentDescription = contentDescription,
cameraPositionState = currentCameraPositionState,
clickListeners = mapClickListeners,
contentPadding = currentContentPadding,
locationSource = currentLocationSource,
mapProperties = currentMapProperties,
mapUiSettings = currentUiSettings,
)
currentContent?.invoke()
}
}
}
}
private suspend inline fun disposingComposition(factory: () -> Composition) {
val composition = factory()
try {
awaitCancellation()
} finally {
composition.dispose()
}
}
private suspend inline fun MapView.newComposition(
parent: CompositionContext,
noinline content: @Composable () -> Unit
): Composition {
val map = awaitMap()
return Composition(
MapApplier(map, this), parent
).apply {
setContent(content)
}
}
/**
* Registers lifecycle observers to the local [MapView].
*/
@Composable
private fun MapLifecycle(mapView: MapView) {
val context = LocalContext.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
val previousState = remember { mutableStateOf(Lifecycle.Event.ON_CREATE) }
DisposableEffect(context, lifecycle, mapView) {
val mapLifecycleObserver = mapView.lifecycleObserver(previousState)
val callbacks = mapView.componentCallbacks()
lifecycle.addObserver(mapLifecycleObserver)
context.registerComponentCallbacks(callbacks)
onDispose {
lifecycle.removeObserver(mapLifecycleObserver)
context.unregisterComponentCallbacks(callbacks)
}
}
}
private fun MapView.lifecycleObserver(previousState: MutableState<Lifecycle.Event>): LifecycleEventObserver =
LifecycleEventObserver { _, event ->
event.targetState
when (event) {
Lifecycle.Event.ON_CREATE -> {
// Skip calling mapView.onCreate if the lifecycle did not go through onDestroy - in
// this case the GoogleMap composable also doesn't leave the composition. So,
// recreating the map does not restore state properly which must be avoided.
if (previousState.value != Lifecycle.Event.ON_STOP) {
this.onCreate(Bundle())
}
}
Lifecycle.Event.ON_START -> this.onStart()
Lifecycle.Event.ON_RESUME -> this.onResume()
Lifecycle.Event.ON_PAUSE -> this.onPause()
Lifecycle.Event.ON_STOP -> this.onStop()
Lifecycle.Event.ON_DESTROY -> this.onDestroy()
else -> throw IllegalStateException()
}
previousState.value = event
}
private fun MapView.componentCallbacks(): ComponentCallbacks =
object : ComponentCallbacks {
override fun onConfigurationChanged(config: Configuration) {}
override fun onLowMemory() {
this@componentCallbacks.onLowMemory()
}
}