我有一张带有代码的地图:
var geoPoints by remember { mutableStateOf(listOf<LatLng>()) }
val markers = mutableListOf<Unit>()
GoogleMapView(
mapGesturesEnabled = mapGesturesEnabled,
onClick = {
// onClick
geoPoints = geoPoints + it
},
cameraPositionState = cameraPositionState,
onMapLoaded = {
isMapLoaded = true
if (!cameraPositionState.isMoving) {
onBoundsChange(
cameraPositionState.projection!!
)
}
},
modifier = modifier
) {
val context = LocalContext.current
if (geoPoints.isNotEmpty()) {
Polygon(
points = geoPoints,
fillColor = Blue2.copy(alpha = 0.1f),
strokeColor = Blue2
)
for (point in geoPoints) {
val markerState = rememberMarkerState(position = LatLng(point.latitude, point.longitude))
val marker = Marker(
state = markerState,
visible = true,
icon = BitmapDescriptorFactory.fromBitmap(getBitmapFromImage(context, R.drawable.ic_marker_polygon)),
draggable = true
)
markers.add(marker)
}
}
}
我的想法是创建一个地图,用户可以在地图上单击,例如3次,就会绘制一个多边形。但是,当用户想要动态更改多边形时,他们可以拖动该多边形的一个角来更改其大小。这可以在撰写中吗?
类似这样的:
这是可能的。
你几乎就在那里。实现这一点的关键是“观察”标记的位置变化。当标记的位置发生变化时,您需要更新
geoPoints
列表中项目的位置。
我已经尽可能地简化了这一点,以便我们可以专注于问题的要点。
var geoPoints by rememberSaveable { mutableStateOf(listOf<LatLng>()) }
val markers = mutableListOf<Unit>()
GoogleMap(
onMapClick = {
geoPoints = geoPoints + it
}
){
if (geoPoints.isNotEmpty()) {
Polygon(
points = geoPoints,
fillColor = Blue.copy(alpha = 0.1f),
strokeColor = Blue
)
for (point in geoPoints) {
val markerState = rememberMarkerState(position = LatLng(point.latitude, point.longitude))
// we are going to observe the change of the marker position here
LaunchedEffect(markerState.position){
// get a mutable copy of the List<LatLng>
val positions = geoPoints.toMutableList()
// get the index of the dragging point
val pointIndex = positions.indexOf(point)
// sanity check
if(pointIndex < 0) {
return@LaunchedEffect
}
// update the list with the new value
positions[pointIndex] = markerState.position
// assign the copy back and trigger recomposition
geoPoints = positions
}
val marker = Marker(
state = markerState,
visible = true,
draggable = true
)
markers.add(marker)
}
}
}
结果: