-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathGoogleMap.kt
More file actions
274 lines (250 loc) · 10.8 KB
/
GoogleMap.kt
File metadata and controls
274 lines (250 loc) · 10.8 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright 2023 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.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.ReusableComposition
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 mergeDescendants deactivates the map for accessibility purposes
* @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(
mergeDescendants: Boolean = false,
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)? = null,
onMapLongClick: ((LatLng) -> Unit)? = null,
onMapLoaded: (() -> Unit)? = null,
onMyLocationButtonClick: (() -> Boolean)? = null,
onMyLocationClick: ((Location) -> Unit)? = null,
onPOIClick: ((PointOfInterest) -> Unit)? = null,
contentPadding: PaddingValues = NoPadding,
content: (@Composable @GoogleMapComposable () -> Unit)? = null,
) {
// When in preview, early return a Box with the received modifier preserving layout
if (LocalInspectionMode.current) {
Box(modifier = modifier)
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 currentContentDescription by rememberUpdatedState(contentDescription)
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, mapClickListeners) {
MapUpdater(
mergeDescendants = mergeDescendants,
contentDescription = currentContentDescription,
cameraPositionState = currentCameraPositionState,
contentPadding = currentContentPadding,
locationSource = currentLocationSource,
mapProperties = currentMapProperties,
mapUiSettings = currentUiSettings,
)
MapClickListenerUpdater()
CompositionLocalProvider(
LocalCameraPositionState provides currentCameraPositionState,
) {
currentContent?.invoke()
}
}
}
}
}
internal suspend inline fun disposingComposition(factory: () -> ReusableComposition) {
val composition = factory()
try {
awaitCancellation()
} finally {
composition.dispose()
}
}
private suspend inline fun MapView.newComposition(
parent: CompositionContext,
mapClickListeners: MapClickListeners,
noinline content: @Composable () -> Unit
): ReusableComposition {
val map = awaitMap()
return ReusableComposition(
MapApplier(map, this, mapClickListeners), parent
).apply {
setContentWithReuse(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)
}
}
DisposableEffect(mapView) {
onDispose {
mapView.onDestroy()
mapView.removeAllViews()
}
}
}
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 -> {
//handled in onDispose
}
else -> throw IllegalStateException()
}
previousState.value = event
}
private fun MapView.componentCallbacks(): ComponentCallbacks =
object : ComponentCallbacks {
override fun onConfigurationChanged(config: Configuration) {}
override fun onLowMemory() {
this@componentCallbacks.onLowMemory()
}
}
public typealias GoogleMapFactory = @Composable () -> Unit
/**
* This method provides a factory pattern for GoogleMap. It can typically be used in tests to provide a default Composable
* of type GoogleMapFactory.
*
* @param modifier Any modifier to be applied.
* @param cameraPositionState The position for the map.
* @param onMapLoaded Listener for the map loaded.
* @param content Any content to be added.
*/
@Composable
public fun googleMapFactory(
modifier: Modifier = Modifier,
cameraPositionState: CameraPositionState = rememberCameraPositionState(),
onMapLoaded: () -> Unit = {},
content: @Composable () -> Unit = {}
): GoogleMapFactory {
return {
val uiSettings by remember { mutableStateOf(MapUiSettings(compassEnabled = false)) }
val mapProperties by remember {
mutableStateOf(MapProperties(mapType = MapType.NORMAL))
}
val mapVisible by remember { mutableStateOf(true) }
if (mapVisible) {
GoogleMap(
modifier = modifier,
cameraPositionState = cameraPositionState,
properties = mapProperties,
uiSettings = uiSettings,
onMapLoaded = onMapLoaded,
content = content
)
}
}
}