Add a platform independent MapContainer that can be called from shared ui
Wraps Google Maps on both Android and iOS Also bumps targetSDK to 36 because it was required by the library.
This commit is contained in:
@@ -20,6 +20,8 @@ plugins {
|
||||
// (org.jetbrains.compose) vilket gör att :shared förblir plattformsneutral.
|
||||
id("org.jetbrains.compose") version "1.9.0"
|
||||
id("com.codingfeline.buildkonfig") version "0.17.1"
|
||||
|
||||
kotlin("native.cocoapods")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
@@ -29,7 +31,7 @@ kotlin {
|
||||
// See: https://kotlinlang.org/docs/multiplatform-discover-project.html#targets
|
||||
androidLibrary {
|
||||
namespace = "app.klottr.shared"
|
||||
compileSdk = 35
|
||||
compileSdk = 36
|
||||
minSdk = 26
|
||||
|
||||
withHostTestBuilder {
|
||||
@@ -76,6 +78,22 @@ kotlin {
|
||||
}
|
||||
}
|
||||
|
||||
// Cocoapods is used for 3rd party library dependencies in iOS
|
||||
cocoapods {
|
||||
version = "1.0.0" // Out version of the podspec
|
||||
ios.deploymentTarget = "14.0"
|
||||
framework {
|
||||
baseName = xcfName
|
||||
isStatic = true
|
||||
}
|
||||
// This generates the cinterop => `platform.GoogleMaps.*`
|
||||
pod("GoogleMaps") // keep version unspecified to track latest podspec
|
||||
{
|
||||
// To support clang modules
|
||||
extraOpts += listOf("-compiler-option", "-fmodules")
|
||||
}
|
||||
}
|
||||
|
||||
// Source set declarations.
|
||||
// Declaring a target automatically creates a source set with the same name. By default, the
|
||||
// Kotlin Gradle Plugin creates additional source sets that depend on each other, since it is
|
||||
@@ -139,6 +157,7 @@ kotlin {
|
||||
implementation(libs.ktor.client.okhttp)
|
||||
implementation("com.google.android.gms:play-services-location:21.3.0") // FusedLocation
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0") // await() på Tasks
|
||||
implementation("com.google.maps.android:maps-compose:6.10.0") // Sep 9, 2025
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
54
shared/shared.podspec
Normal file
54
shared/shared.podspec
Normal file
@@ -0,0 +1,54 @@
|
||||
Pod::Spec.new do |spec|
|
||||
spec.name = 'shared'
|
||||
spec.version = '1.0.0'
|
||||
spec.homepage = ''
|
||||
spec.source = { :http=> ''}
|
||||
spec.authors = ''
|
||||
spec.license = ''
|
||||
spec.summary = ''
|
||||
spec.vendored_frameworks = 'build/cocoapods/framework/shared.framework'
|
||||
spec.libraries = 'c++'
|
||||
spec.ios.deployment_target = '14.0'
|
||||
spec.dependency 'GoogleMaps'
|
||||
|
||||
if !Dir.exist?('build/cocoapods/framework/shared.framework') || Dir.empty?('build/cocoapods/framework/shared.framework')
|
||||
raise "
|
||||
|
||||
Kotlin framework 'shared' doesn't exist yet, so a proper Xcode project can't be generated.
|
||||
'pod install' should be executed after running ':generateDummyFramework' Gradle task:
|
||||
|
||||
./gradlew :shared:generateDummyFramework
|
||||
|
||||
Alternatively, proper pod installation is performed during Gradle sync in the IDE (if Podfile location is set)"
|
||||
end
|
||||
|
||||
spec.xcconfig = {
|
||||
'ENABLE_USER_SCRIPT_SANDBOXING' => 'NO',
|
||||
}
|
||||
|
||||
spec.pod_target_xcconfig = {
|
||||
'KOTLIN_PROJECT_PATH' => ':shared',
|
||||
'PRODUCT_MODULE_NAME' => 'shared',
|
||||
}
|
||||
|
||||
spec.script_phases = [
|
||||
{
|
||||
:name => 'Build shared',
|
||||
:execution_position => :before_compile,
|
||||
:shell_path => '/bin/sh',
|
||||
:script => <<-SCRIPT
|
||||
if [ "YES" = "$OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED" ]; then
|
||||
echo "Skipping Gradle build task invocation due to OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED environment variable set to \"YES\""
|
||||
exit 0
|
||||
fi
|
||||
set -ev
|
||||
REPO_ROOT="$PODS_TARGET_SRCROOT"
|
||||
"$REPO_ROOT/../gradlew" -p "$REPO_ROOT" $KOTLIN_PROJECT_PATH:syncFramework \
|
||||
-Pkotlin.native.cocoapods.platform=$PLATFORM_NAME \
|
||||
-Pkotlin.native.cocoapods.archs="$ARCHS" \
|
||||
-Pkotlin.native.cocoapods.configuration="$CONFIGURATION"
|
||||
SCRIPT
|
||||
}
|
||||
]
|
||||
spec.resources = ['build/compose/cocoapods/compose-resources']
|
||||
end
|
||||
@@ -0,0 +1,114 @@
|
||||
package app.klottr.maps
|
||||
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.google.android.gms.maps.CameraUpdateFactory
|
||||
import com.google.maps.android.compose.*
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private class AndroidMapController(
|
||||
private val cameraState: CameraPositionState,
|
||||
private val onSetFeatures: (List<MapFeature>) -> Unit,
|
||||
private val myLocationSetter: (Boolean) -> Unit,
|
||||
private val scope: CoroutineScope,
|
||||
) : MapController {
|
||||
private val _camera = MutableSharedFlow<CameraPosition>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
|
||||
override val cameraPosition = _camera.asSharedFlow()
|
||||
override fun moveCamera(position: CameraPosition) {
|
||||
cameraState.move(
|
||||
CameraUpdateFactory.newCameraPosition(
|
||||
com.google.android.gms.maps.model.CameraPosition.fromLatLngZoom(
|
||||
com.google.android.gms.maps.model.LatLng(position.target.latitude, position.target.longitude),
|
||||
position.zoom
|
||||
)
|
||||
))
|
||||
}
|
||||
override fun animateCamera(position: CameraPosition) {
|
||||
// Fire-and-forget on the main scope (rememberCoroutineScope()).
|
||||
scope.launch {
|
||||
cameraState.animate(
|
||||
CameraUpdateFactory.newCameraPosition(
|
||||
com.google.android.gms.maps.model.CameraPosition.fromLatLngZoom(
|
||||
com.google.android.gms.maps.model.LatLng(position.target.latitude, position.target.longitude),
|
||||
position.zoom
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
override fun setFeatures(features: List<MapFeature>) = onSetFeatures(features)
|
||||
override fun clear() = onSetFeatures(emptyList())
|
||||
override fun setMyLocationEnabled(enabled: Boolean) = myLocationSetter(enabled)
|
||||
}
|
||||
|
||||
@Composable
|
||||
actual fun MapContainer(
|
||||
state: MapState,
|
||||
onMapClick: ((LatLng) -> Unit)?,
|
||||
onMarkerClick: ((id: String) -> Unit)?,
|
||||
onReady: (MapController) -> Unit,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val cameraState = rememberCameraPositionState {
|
||||
position = com.google.android.gms.maps.model.CameraPosition.fromLatLngZoom(
|
||||
com.google.android.gms.maps.model.LatLng(state.camera.target.latitude, state.camera.target.longitude),
|
||||
state.camera.zoom
|
||||
)
|
||||
}
|
||||
|
||||
var features by remember { mutableStateOf(state.features) }
|
||||
var myLocationEnabled by remember { mutableStateOf(false) }
|
||||
|
||||
val controller = remember(cameraState) {
|
||||
AndroidMapController(
|
||||
cameraState = cameraState,
|
||||
onSetFeatures = { features = it },
|
||||
myLocationSetter = { myLocationEnabled = it },
|
||||
scope = scope
|
||||
)
|
||||
}
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onReady(controller)
|
||||
onDispose { }
|
||||
}
|
||||
|
||||
GoogleMap(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
cameraPositionState = cameraState,
|
||||
uiSettings = com.google.maps.android.compose.MapUiSettings(
|
||||
compassEnabled = state.ui.compassEnabled,
|
||||
zoomControlsEnabled = state.ui.zoomControlsEnabled,
|
||||
myLocationButtonEnabled = state.ui.myLocationButtonEnabled
|
||||
),
|
||||
properties = MapProperties(isMyLocationEnabled = myLocationEnabled),
|
||||
onMapClick = { latLng ->
|
||||
onMapClick?.invoke(LatLng(latLng.latitude, latLng.longitude))
|
||||
},
|
||||
onPOIClick = { /* optional */ },
|
||||
) {
|
||||
features.forEach { f ->
|
||||
when (f) {
|
||||
is MapFeature.Marker -> Marker(
|
||||
state = MarkerState(
|
||||
position = com.google.android.gms.maps.model.LatLng(
|
||||
f.position.latitude, f.position.longitude
|
||||
)
|
||||
),
|
||||
title = f.title,
|
||||
snippet = f.snippet,
|
||||
draggable = f.draggable,
|
||||
onClick = {
|
||||
onMarkerClick?.invoke(f.id)
|
||||
true
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
shared/src/commonMain/kotlin/app/klottr/maps/MapContainer.kt
Normal file
52
shared/src/commonMain/kotlin/app/klottr/maps/MapContainer.kt
Normal file
@@ -0,0 +1,52 @@
|
||||
package app.klottr.maps
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
data class LatLng(val latitude: Double, val longitude: Double)
|
||||
data class CameraPosition(val target: LatLng, val zoom: Float = 12f)
|
||||
|
||||
sealed interface MapFeature {
|
||||
data class Marker(
|
||||
val id: String,
|
||||
val position: LatLng,
|
||||
val title: String? = null,
|
||||
val snippet: String? = null,
|
||||
val draggable: Boolean = false,
|
||||
) : MapFeature
|
||||
// Add Polyline/Polygon later if needed
|
||||
}
|
||||
|
||||
data class MapUiSettings(
|
||||
val compassEnabled: Boolean = true,
|
||||
val zoomControlsEnabled: Boolean = false,
|
||||
val myLocationButtonEnabled: Boolean = false,
|
||||
)
|
||||
|
||||
interface MapController {
|
||||
val cameraPosition: Flow<CameraPosition>
|
||||
fun moveCamera(position: CameraPosition)
|
||||
fun animateCamera(position: CameraPosition)
|
||||
fun setFeatures(features: List<MapFeature>)
|
||||
fun clear()
|
||||
fun setMyLocationEnabled(enabled: Boolean) // no-op on iOS if not granted
|
||||
}
|
||||
|
||||
class MapState(
|
||||
initialCamera: CameraPosition = CameraPosition(LatLng(0.0, 0.0), 2f),
|
||||
initialUi: MapUiSettings = MapUiSettings(),
|
||||
initialFeatures: List<MapFeature> = emptyList()
|
||||
) {
|
||||
var camera: CameraPosition = initialCamera
|
||||
var ui: MapUiSettings = initialUi
|
||||
var features: List<MapFeature> = initialFeatures
|
||||
}
|
||||
|
||||
/** Platform container composable. Returns a controller when ready. */
|
||||
@Composable
|
||||
expect fun MapContainer(
|
||||
state: MapState,
|
||||
onMapClick: ((LatLng) -> Unit)? = null,
|
||||
onMarkerClick: ((id: String) -> Unit)? = null,
|
||||
onReady: (MapController) -> Unit = {},
|
||||
)
|
||||
@@ -24,6 +24,8 @@ import kotlinx.serialization.json.Json
|
||||
object WikipediaShared {
|
||||
|
||||
// En HttpClient per process – återanvänds (lazy).
|
||||
// OH: Jag gjorde denna publik så den kan användas av WikiThumb.
|
||||
// OH: Det finns nu fyra olika httpclients i appen (wiki, fornsök, klottr, dm), behövs det eller kan vi dela?
|
||||
val client by lazy {
|
||||
HttpClient(platformEngine()) {
|
||||
// JSON-konfiguration: tolerant och ignorera okända fält
|
||||
|
||||
139
shared/src/iosMain/kotlin/app/klottr/maps/MapContainer.ios.kt
Normal file
139
shared/src/iosMain/kotlin/app/klottr/maps/MapContainer.ios.kt
Normal file
@@ -0,0 +1,139 @@
|
||||
@file:OptIn(ExperimentalForeignApi::class)
|
||||
|
||||
package app.klottr.maps
|
||||
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.interop.UIKitView
|
||||
import cocoapods.GoogleMaps.GMSMapView
|
||||
import kotlinx.cinterop.ExperimentalForeignApi
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import platform.CoreGraphics.CGRectZero
|
||||
import platform.CoreLocation.CLLocationCoordinate2D
|
||||
import platform.CoreLocation.CLLocationCoordinate2DMake
|
||||
import cocoapods.GoogleMaps.* // from GoogleMaps iOS SDK
|
||||
import kotlinx.cinterop.CValue
|
||||
import kotlinx.cinterop.readValue
|
||||
import kotlinx.cinterop.useContents
|
||||
import platform.UIKit.UIView
|
||||
import platform.darwin.NSObject
|
||||
|
||||
private class IOSMapController(
|
||||
private val mapView: GMSMapView,
|
||||
private val featureApplier: (List<MapFeature>) -> Unit
|
||||
) : MapController {
|
||||
private val _camera = MutableSharedFlow<CameraPosition>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
|
||||
override val cameraPosition = _camera.asSharedFlow()
|
||||
|
||||
override fun moveCamera(position: CameraPosition) {
|
||||
mapView.camera = GMSCameraPosition.cameraWithTarget(
|
||||
CLLocationCoordinate2DMake(position.target.latitude, position.target.longitude),
|
||||
position.zoom
|
||||
)
|
||||
}
|
||||
override fun animateCamera(position: CameraPosition) {
|
||||
val update = GMSCameraUpdate.setTarget(
|
||||
CLLocationCoordinate2DMake(position.target.latitude, position.target.longitude),
|
||||
position.zoom
|
||||
)
|
||||
mapView.animateWithCameraUpdate(update)
|
||||
}
|
||||
override fun setFeatures(features: List<MapFeature>) = featureApplier(features)
|
||||
override fun clear() = featureApplier(emptyList())
|
||||
override fun setMyLocationEnabled(enabled: Boolean) {
|
||||
mapView.myLocationEnabled = enabled
|
||||
mapView.settings.myLocationButton = enabled
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalForeignApi::class)
|
||||
@Composable
|
||||
actual fun MapContainer(
|
||||
state: MapState,
|
||||
onMapClick: ((LatLng) -> Unit)?,
|
||||
onMarkerClick: ((id: String) -> Unit)?,
|
||||
onReady: (MapController) -> Unit,
|
||||
) {
|
||||
var mapViewRef by remember { mutableStateOf<GMSMapView?>(null) }
|
||||
var features by remember { mutableStateOf(state.features) }
|
||||
|
||||
UIKitView(
|
||||
factory = {
|
||||
val camera = GMSCameraPosition.cameraWithTarget(
|
||||
CLLocationCoordinate2DMake(state.camera.target.latitude, state.camera.target.longitude),
|
||||
state.camera.zoom
|
||||
)
|
||||
val mv = GMSMapView.mapWithFrame(frame = CGRectZero.readValue(), camera = camera)
|
||||
mv.settings.compassButton = state.ui.compassEnabled
|
||||
mv.settings.zoomGestures = true
|
||||
mv.settings.scrollGestures = true
|
||||
mv.settings.myLocationButton = state.ui.myLocationButtonEnabled
|
||||
mv.setDelegate(object : NSObject(), GMSMapViewDelegateProtocol {
|
||||
|
||||
|
||||
override fun mapView(mapView: GMSMapView, didLongPressAtCoordinate: CValue<CLLocationCoordinate2D>) {
|
||||
didLongPressAtCoordinate.useContents {
|
||||
val lat = latitude
|
||||
val lng = longitude
|
||||
onMapClick?.invoke(LatLng(lat, lng))
|
||||
}
|
||||
}
|
||||
override fun mapView(mapView: GMSMapView, didTapMarker: GMSMarker): Boolean {
|
||||
val id = didTapMarker.userData as? String ?: return false
|
||||
onMarkerClick?.invoke(id)
|
||||
return true
|
||||
}
|
||||
|
||||
})
|
||||
mapViewRef = mv
|
||||
// initial features
|
||||
applyFeatures(mv, features)
|
||||
mv
|
||||
},
|
||||
modifier = Modifier,
|
||||
update = { mv: UIView ->
|
||||
(mv as GMSMapView).let { map ->
|
||||
// update UI toggles
|
||||
map.settings.compassButton = state.ui.compassEnabled
|
||||
map.settings.myLocationButton = state.ui.myLocationButtonEnabled
|
||||
// update camera if changed (best-effort)
|
||||
// (Optional: compare current camera to state.camera)
|
||||
// re-apply features if list changed
|
||||
if (features !== state.features) {
|
||||
features = state.features
|
||||
applyFeatures(map, features)
|
||||
}
|
||||
}
|
||||
},
|
||||
onRelease = {
|
||||
mapViewRef = null
|
||||
}
|
||||
)
|
||||
|
||||
// Expose controller once
|
||||
LaunchedEffect(mapViewRef) {
|
||||
mapViewRef?.let { mv ->
|
||||
onReady(IOSMapController(mv) { applyFeatures(mv, it) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyFeatures(map: GMSMapView, features: List<MapFeature>) {
|
||||
// Clear existing markers
|
||||
map.clear()
|
||||
features.forEach { f ->
|
||||
when (f) {
|
||||
is MapFeature.Marker -> {
|
||||
val marker = GMSMarker()
|
||||
marker.position = CLLocationCoordinate2DMake(f.position.latitude, f.position.longitude)
|
||||
marker.title = f.title
|
||||
marker.snippet = f.snippet
|
||||
marker.userData = f.id
|
||||
marker.map = map
|
||||
marker.draggable = f.draggable
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user