Home > Net >  Creating mutiple markers on google maps in compose
Creating mutiple markers on google maps in compose

Time:09-15

I am trying to create mutiple markers on a google map using compose. I also want to be able to add and remove markers. This is what I have created so far(see below). A list of countries from a data class with longitude and latitude coordinates.

What would be the best approach ?

@HiltViewModel
class LocationsViewModel @Inject constructor(): ViewModel() {

    data class AllPositions(
        val name: String,
        val lat: Double,
        val lng: Double
    )

    fun addAllPositions() = listOf(

        AllPositions("Stockholm",59.3252671500249, 18.06892284219277),
        AllPositions("Berlin",52.5210668493763, 13.437903189993865),
        AllPositions("Warszawa",52.215711901711245, 20.996237421187725),
        AllPositions("Paris",48.84465430007765, 2.270300780605712)
    )
}

My Google Maps composable:

@ExperimentalPermissionsApi
@Composable
fun RequestPermission(
    permission: String,
    rationaleMessage: String = "To use this app's functionalities, you need to give us the permission.",
    viewModel: LocationsViewModel = hiltViewModel()
) {
    val permissionState = rememberPermissionState(permission)
    val countries = viewModel.addAllPositions()
    val cameraPositionState: CameraPositionState = rememberCameraPositionState {
        position = CameraPosition.fromLatLngZoom(LatLng(countries.toString().toDouble(), countries.toString().toDouble()), 11.8f)
    }

    HandleRequest(
        permissionState = permissionState,
        deniedContent = { shouldShowRationale ->
            PermissionDeniedContent(
                rationaleMessage = rationaleMessage,
                shouldShowRationale = shouldShowRationale
            ) { permissionState.launchPermissionRequest() }
        },
        content = {
            // if granted permission, content goes here

                GoogleMap(
                    modifier = Modifier.fillMaxSize(),
                    cameraPositionState = cameraPositionState,
                    properties = properties,
                    uiSettings = uiSettings
                ) {

                  // How do solve this ?? 

                    countries.forEach {
                        position ->
                        Marker(
                            state = ??
                            title = ??,
                            snippet = ??
                        )
                    }
                }
        }
    )
}

CodePudding user response:

You need to pass MarkerState() in Marker() with required LatLng() as parameter.

countries.forEach { position ->
    Marker(
        state = MarkerState(
            position = LatLng(
                position.lat,
                position.lng
            ),
        title = position.name
        )
    )
}
  • Related