kotlin 如何在Jetpack Compose中在Google Maps上拖动标记时使用InputHandler?

r6hnlfcb  于 2023-04-07  发布在  Kotlin
关注(0)|答案(1)|浏览(172)

我已经在GoogleMap上成功添加了这个标记:

Marker(
    state = MarkerState(
        position = LatLng(lat, lng)
    ),
    title = "Party",
    snippet = "Come to party.",
    draggable = true
)

我把它设置为可拖动的。现在我想知道什么时候有人拖动它。我发现这个函数叫InputHandler(),但我不知道如何使用它。
我尝试使用:

InputHandler(
    onMarkerDragEnd = { marker ->
        Log.d(TAG, "${marker.id}")
    }
)

但是什么也没有发生。有人能帮忙吗?或者有什么其他的想法来知道什么时候拖动标记?

fwzugrvs

fwzugrvs1#

可以使用OnMarkerDragListener接口侦听标记拖动事件。

val marker = googleMap.addMarker(
    MarkerOptions()
        .position(LatLng(lat, lng))
        .title("Location")
        .snippet("set Location.")
        .draggable(true)
)

googleMap.setOnMarkerDragListener(object : OnMarkerDragListener {
    override fun onMarkerDragStart(marker: Marker?) {
        // Called when marker drag starts
    }

    override fun onMarkerDrag(marker: Marker?) {
        // Called while marker is being dragged
    }

    override fun onMarkerDragEnd(marker: Marker?) {
        // Called when marker drag ends
        Log.d(TAG, "${marker?.id}")
    }
})

这里是Formaps-compose

var markerPosition by remember { mutableStateOf(LatLng(37.7749, -122.4194)) }
var isDragging by remember { mutableStateOf(false) }

GoogleMap(
    modifier = Modifier.fillMaxSize(),
    initialCameraPosition = CameraPosition(target = markerPosition, zoom = 10f),
    onMapClick = { /* handle map clicks */ }
) { map ->
    if (isDragging) {
        // While dragging, create a temporary marker with opacity set to 0
        Marker(
            position = markerPosition,
            alpha = 0f
        )
    } else {
        // When not dragging, create a visible marker
        Marker(
            position = markerPosition,
            title = "Party",
            snippet = "Come to party.",
            draggable = true,
            onClick = { /* handle marker clicks */ }
        )
    }
}

// Listen for drag events using the pointer input system
PointerInput(Unit) {
    forEachGesture {
        awaitPointerEventScope {
            val down = awaitFirstDown()
            if (down.changes.any { it.changedToDown() && it.position in markerPosition.toOffset() }) {
                // If the user starts a drag gesture on the marker, set isDragging to true
                isDragging = true
            }

            val up = awaitUpOrCancellation()
            if (up.changes.any { it.changedToUp() }) {
                // If the user stops a drag gesture, set isDragging to false and update the marker position
                isDragging = false
                markerPosition = up.changes.first { it.changedToUp() }.position.toLatLng()
            }
        }
    }
}

相关问题