<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Attila Polacsek on Medium]]></title>
        <description><![CDATA[Stories by Attila Polacsek on Medium]]></description>
        <link>https://medium.com/@apolacsek?source=rss-c68baa516378------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*q4ZDG7XgSWf_aElT</url>
            <title>Stories by Attila Polacsek on Medium</title>
            <link>https://medium.com/@apolacsek?source=rss-c68baa516378------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:54:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@apolacsek/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating MapKit in Compose Multiplatform — Part 2: Refining implementation]]></title>
            <link>https://medium.com/supercharges-mobile-product-guide/integrating-mapkit-in-compose-multiplatform-part-2-refining-implementation-d498b6aef96c?source=rss-c68baa516378------2</link>
            <guid isPermaLink="false">https://medium.com/p/d498b6aef96c</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[mapkit]]></category>
            <dc:creator><![CDATA[Attila Polacsek]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 08:59:17 GMT</pubDate>
            <atom:updated>2025-02-03T08:59:17.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWoix08yXRMEyyW2JyJpng.jpeg" /></figure><h3>Integrating MapKit in Compose Multiplatform — Part 2: Refining implementation</h3><p>In the <a href="https://medium.com/supercharges-mobile-product-guide/integrating-mapkit-in-compose-multiplatform-165de6141364">previous article</a>, we explored the fundamentals of integrating Apple’s MapKit into a Compose Multiplatform application. We covered the basics of UIKitView integration, marker placement and route visualization. While the implementation got us up and running with native maps, it didn’t fully embrace Compose’s declarative paradigm and state management patterns.</p><p>In this article we will refactor our previous MapKit integration into a more idiomatic Compose implementation, making it more maintainable and reusable.</p><h4>Before We Begin: Handling Touch Events</h4><p>While implementing our previous map integration, you might have noticed that map interactions felt somewhat unresponsive. This wasn’t a significant issue for our static map display, but as we move towards a more interactive implementation, we need to address this limitation.</p><p>The challenge arises from how Compose handles touch events. By default, Compose intercepts all touch events, which can interfere with MapKit’s native gesture handling. To ensure our map responds naturally to user interactions, we need to adjust how UIKitView processes these events:</p><pre>UIKitView(<br>   modifier = modifier,<br>   properties = UIKitInteropProperties(<br>       interactionMode = UIKitInteropInteractionMode.NonCooperative<br>   ),<br>   factory = {<br>       ...<br>   },<br>   update = { mapView -&gt;<br>       ...<br>   }<br>)</pre><p>By setting the interaction mode to <a href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-ios-migration.html#touches-or-gestures-may-stop-working-as-expected">NonCooperative</a>, we tell Compose to step aside and let MapKit handle all touch and gesture events directly. While <a href="https://github.com/JetBrains/compose-multiplatform/releases/tag/v1.7.3">Compose 1.7.3</a> introduced improvements for basic touch events, this property remains essential for proper handling of complex gestures like dragging and swiping that are crucial for map navigation.</p><p>With this small but important adjustment in place, we’re ready to begin transforming our map implementation into a more idiomatic Compose integration.</p><h4>Generalizing Our Map Implementation</h4><p>Our current map implementation has two key limitations. First, it’s tightly coupled to specific use cases, making it difficult to adapt for different scenarios. Second, any customization requires platform-specific implementations rather than being handled in our common codebase. Let’s address these issues by making our map component more dynamic and truly Compose-native.</p><p>Before Google’s official Compose Maps library was available, we needed to integrate Google Maps into a Compose-based UI. Our solution was to move the MapView creation into a separate remember composable function instead of instantiating it directly in AndroidView’s factory callback. This pattern proved highly effective, allowing us to share the map instance across multiple composables. We can now apply this same battle-tested approach to our MKMapView implementation.</p><p>Let’s start by updating our CommonMap to be more flexible and reusable:</p><pre>@Composable<br>expect fun CommonMap(<br>   modifier: Modifier = Modifier,<br>   contentPadding: PaddingValues = PaddingValues(0.dp),<br>   content: @Composable @CommonMapComposable () -&gt; Unit = {}<br>)</pre><p>This updated signature introduces two significant changes. First, the API now uses a content lambda parameter instead of accepting specific data types. This shift to a more compositional approach provides greater flexibility in defining and rendering the map’s content. Additionally, a contentPadding parameter has been added to control the spacing between the map’s content, such as the Apple logo and legal text, and its boundaries.</p><p>The @CommonMapComposable annotation deserves special mention. It’s a custom <a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/ComposableTargetMarker">@ComposableTargetMarker</a> that we’ve type-aliased to <a href="https://github.com/googlemaps/android-maps-compose/blob/main/maps-compose/src/main/java/com/google/maps/android/compose/GoogleMapComposable.kt">@GoogleMapComposable</a> for compatibility. This annotation helps enforce proper usage patterns, composable functions marked with this annotation should only be used within other composables that share the same annotation. The compiler will warn developers if these composables are used incorrectly.</p><h4>Remembering Our Map View</h4><p>Now that we’ve established our general approach, let’s implement a remember function for MKMapView that aligns with Compose’s lifecycle management:</p><pre>@Composable<br>fun rememberMkMapView(): MKMapView {<br>   val mapView = remember { MKMapView() }<br><br>   DisposableEffect(mapView) {<br>       onDispose {<br>           mapView.setDelegate(null)<br>           mapView.removeAnnotations(mapView.annotations)<br>           mapView.removeOverlays(mapView.overlays)<br>       }<br>   }<br><br>   return mapView<br>}<br><br>val LocalMapView = staticCompositionLocalOf&lt;MKMapView&gt; {<br>   error(&quot;No LocalMapView provided&quot;)<br>}</pre><p>Using remember ensures the MKMapView persists across recompositions, avoiding unnecessary recreations. Second, we properly handle cleanup through a DisposableEffect. When the composable leaves the composition, the effect ensures we clear all delegates, annotations, and overlays, preventing memory leaks and ensuring proper resource management.</p><p>We also introduce a CompositionLocal for our map view using staticCompositionLocalOf. This allows us to make the map instance available to child composables without explicit passing. The static variant is chosen because our map view instance won’t change during the composition’s lifetime, and we want to minimize unnecessary recompositions.</p><h4>Implementing Our Composable Map</h4><p>With our foundation in place, let’s implement the iOS-specific version of our CommonMap:</p><pre>@Composable<br>actual fun CommonMap(<br>   modifier: Modifier,<br>   contentPadding: PaddingValues,<br>   content: @Composable @CommonMapComposable () -&gt; Unit<br>) {<br>   val mkMapView = rememberMkMapView()<br>   val mkMapViewDelegate = rememberMKMapViewDelegate()<br><br>   AppleMap(<br>       modifier = modifier,<br>       mkMapView = mkMapView,<br>       mkMapViewDelegate = mkMapViewDelegate,<br>       contentPadding = contentPadding,<br>       content = content<br>   )<br>}</pre><p>Our actual implementation serves primarily as a wrapper, creating and managing the map view and delegate as states. The real work happens in our AppleMap composable, which encapsulates all map-related updates and configurations:</p><pre>@Composable<br>private fun AppleMap(<br>   modifier: Modifier = Modifier,<br>   mkMapView: MKMapView = rememberMkMapView(),<br>   mkMapViewDelegate: MKMapViewDelegateProtocol = rememberMKMapViewDelegate(),<br>   contentPadding: PaddingValues = PaddingValues(0.dp),<br>   content: @Composable () -&gt; Unit<br>) {<br>   val layoutDirection = LocalLayoutDirection.current<br><br>   val directionalEdgeInsets = remember(layoutDirection, contentPadding) {<br>       NSDirectionalEdgeInsetsMake(<br>           top = contentPadding.calculateTopPadding().value.toDouble(),<br>           leading = contentPadding.calculateStartPadding(layoutDirection).value.toDouble(),<br>           bottom = contentPadding.calculateBottomPadding().value.toDouble(),<br>           trailing = contentPadding.calculateEndPadding(layoutDirection).value.toDouble()<br>       )<br>   }<br><br>   UIKitView(<br>       modifier = modifier,<br>       properties = UIKitInteropProperties(<br>           interactionMode = UIKitInteropInteractionMode.NonCooperative<br>       ),<br>       factory = {<br>           mkMapView.apply {<br>               setZoomEnabled(true)<br>               setScrollEnabled(true)<br>               setRotateEnabled(true)<br>               setPitchEnabled(true)<br>               setShowsCompass(false)<br>               // customize map view further<br>           }<br>       },<br>       update = { mapView -&gt;<br>           mapView.delegate = mkMapViewDelegate<br>           mapView.directionalLayoutMargins = directionalEdgeInsets<br>       }<br>   )<br><br>   CompositionLocalProvider(LocalMapView provides mkMapView) {<br>       content()<br>   }<br>}</pre><p>This implementation builds upon our previous work while introducing several improvements. Map state management has been moved outside the UIKitView. Content padding is now handled through NSDirectionalEdgeInsets, which respects the layout direction, ensuring a more intuitive layout. Furthermore, the map instance is provided to child composables through CompositionLocal.</p><p>This structure ensures that updates to the map view or delegate won’t trigger unnecessary recompositions of the entire component. Only the specific parts that need to change will be updated.</p><p>While we could further improve this by creating a common configuration class for map parameters like zoom, scroll, and rotation settings, these are hardcoded in the example for simplicity. In a production environment, you’d likely want to make these configurable through the component’s API.</p><h4>Creating Composable Map Content</h4><p>Now that we have our base map implementation, let’s transform our content elements from data classes into composable functions loosely following the naming established by the Google Maps Compose library.</p><pre>@Composable<br>@CommonMapComposable<br>expect fun MarkerComposable(<br>   vararg keys: Any,<br>   position: LatLng,<br>   anchor: Offset = Offset(0.5f, 1.0f),<br>   infoContent: (@Composable () -&gt; Unit)? = null,<br>   content: @Composable () -&gt; Unit<br>)<br><br>@Composable<br>@CommonMapComposable<br>expect fun MarkerInfoWindowComposable(<br>   vararg keys: Any,<br>   position: LatLng,<br>   anchor: Offset = Offset(0.5f, 1.0f),<br>   infoContent: (@Composable () -&gt; Unit)? = null,<br>   content: @Composable () -&gt; Unit<br>)<br><br>@Composable<br>@CommonMapComposable<br>expect fun Polyline(<br>   points: ImmutableList&lt;LatLng&gt;,<br>   color: Color = Color.Black,<br>   width: Dp = 2.dp<br>)</pre><p>We’ve also introduced a platform-agnostic LatLng class, following Google Maps naming convention here as well, to handle geographical coordinates consistently across platforms. With this abstraction, we can centralize coordinate mapping logic in our common code, reducing platform-specific implementations and creating a more uniform API.</p><h4>Implementing Composable Polylines</h4><p>Let’s start by refactoring our polyline implementation to be more flexible and composable. First, we’ll create a generic overlay wrapper that can handle different types of map overlays:</p><pre>class CommonMapOverlay(<br>   private val delegate: MKOverlayProtocol,<br>   private val rendererCreator: (MKOverlayProtocol) -&gt; MKOverlayRenderer<br>) : NSObject(), MKOverlayProtocol {<br><br>   override fun coordinate(): CValue&lt;CLLocationCoordinate2D&gt; = delegate.coordinate()<br><br>   override fun boundingMapRect(): CValue&lt;MKMapRect&gt; = delegate.boundingMapRect()<br><br>   fun createRenderer(): MKOverlayRenderer = rendererCreator(delegate)<br>}</pre><p>This wrapper class serves a dual purpose. It implements the required MKOverlayProtocol while allowing us to customize how the overlay is rendered through a callback function. We use composition instead of inheritance since we need to implement an Objective-C protocol and the <a href="https://kotlinlang.org/docs/native-objc-interop.html#subclassing-swift-objective-c-classes-and-protocols-from-kotlin">implementation must be final</a>.</p><p>With this wrapper in place, we can simplify our delegate implementation:</p><pre>@ObjCSignatureOverride<br>override fun mapView(mapView: MKMapView, rendererForOverlay: MKOverlayProtocol): MKOverlayRenderer {<br>   val overlay = rendererForOverlay as? CommonMapOverlay ?: return MKOverlayRenderer(rendererForOverlay)<br><br>   return overlay.createRenderer()<br>}</pre><p>Let’s update our remember function as well to use this new overlay system:</p><pre>@Composable<br>private fun rememberPolylineOverlay(<br>   points: ImmutableList&lt;LatLng&gt;,<br>   color: Color,<br>   width: Dp<br>): MKOverlayProtocol {<br>   val polyline = remember(points) {<br>       // Polyline creation code remains the same<br>   }<br><br>   // Note: we use points as the key instead of the polyline since points is Stable<br>   return remember(points, color, width) {<br>       CommonMapOverlay(<br>           delegate = polyline,<br>           rendererCreator = {<br>               MKPolylineRenderer(overlay = polyline).apply {<br>                   setStrokeColor(color.toUIColor())<br>                   setLineWidth(width.value.toDouble())<br>                   setLineCap(CGLineCap.kCGLineCapRound)<br>               }<br>           }<br>       )<br>   }<br>}</pre><p>Finally, we can implement our composable polyline function:</p><pre>@Composable<br>@CommonMapComposable<br>actual fun Polyline(<br>   points: ImmutableList&lt;LatLng&gt;,<br>   color: Color,<br>   width: Dp<br>) {<br>   val mapView = LocalMapView.current<br>   val overlay = rememberPolylineOverlay(points, color, width)<br><br>   DisposableEffect(mapView, points, color, width) {<br>       mapView.addOverlay(overlay)<br><br>       onDispose {<br>           mapView.removeOverlay(overlay)<br>       }<br>   }<br>}</pre><p>We start by retrieving the map instance from our CompositionLocal, then create and remember the overlay with our custom styling. The overlay’s lifecycle is managed through a DisposableEffect, which handles both the initial addition to the map and subsequent updates whenever parameters change. When the composable leaves the composition, the effect ensures proper cleanup by removing the overlay from the map.</p><h4>Creating Custom Markers</h4><p>To support custom markers we must create a custom MKAnnotation that works with MapKit’s view recycling mechanism. Our implementation draws inspiration from Android’s ViewHolder pattern, providing efficient view reuse.</p><p>First, let’s create our custom annotation class:</p><pre>class CommonMapAnnotation(<br>   val identifier: String,<br>   private val position: LatLng,<br>   private val viewCreator: (MKAnnotationProtocol) -&gt; MKAnnotationView,<br>   private val viewBinder: (MKAnnotationView) -&gt; Unit<br>): NSObject(), MKAnnotationProtocol {<br><br>   override fun coordinate(): CValue&lt;CLLocationCoordinate2D&gt; = position.data<br><br>   fun createView(): MKAnnotationView = viewCreator(this)<br><br>   fun bindView(view: MKAnnotationView) = viewBinder(view)<br>}</pre><p>This annotation class serves several purposes. It holds the marker’s position and identifier, provides callbacks for view creation and binding, and implements MapKit’s annotation protocol for proper integration.</p><p>Next, we need to update our map delegate to handle these custom annotations:</p><pre>@ObjCSignatureOverride<br>override fun mapView(mapView: MKMapView, viewForAnnotation: MKAnnotationProtocol): MKAnnotationView? {<br>   val annotation = viewForAnnotation as? CommonMapAnnotation ?: return null<br><br>   var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotation.identifier)<br><br>   if (annotationView == null) {<br>       annotationView = annotation.createView()<br>   } else {<br>       annotationView.annotation = viewForAnnotation<br>   }<br><br>   annotation.bindView(annotationView)<br><br>   return annotationView<br>}</pre><p>This delegate implementation uses MapKit’s <a href="https://developer.apple.com/documentation/mapkit/mkmapview/1452672-dequeuereusableannotationviewwit">view recycling</a>. The system first attempts to reuse an existing view with the same identifier. If no recyclable view is available, it creates a new one. The view is then updated with the current annotation data, and finally, the latest content is bound to the view.</p><h4>Implementing Markers with Info Windows</h4><p>Now let’s create our marker implementation that supports custom content and info windows. The implementation handles both the marker’s appearance and its optional info window:</p><pre>@CommonMapComposable<br>@Composable<br>actual fun MarkerInfoWindowComposable(<br>   vararg keys: Any,<br>   position: LatLng,<br>   anchor: Offset,<br>   infoContent: @Composable (() -&gt; Unit)?,<br>   content: @Composable () -&gt; Unit<br>) {<br>   val density = LocalDensity.current<br>   val mapView = LocalMapView.current<br><br>   var annotation by remember { mutableStateOf&lt;CommonMapAnnotation?&gt;(null) }<br><br>   val contentGraphicsLayer = rememberGraphicsLayer()<br>   val currentContent by rememberUpdatedState(content)<br><br>   val infoContentGraphicsLayer = rememberGraphicsLayer()<br>   val currentInfoContent by rememberUpdatedState(infoContent)<br><br>   Box(<br>       modifier = Modifier.drawWithContent {<br>           contentGraphicsLayer.record { this@drawWithContent.drawContent() }<br>       }<br>   ) {<br>       currentContent()<br>   }<br><br>   if (currentInfoContent != null) {<br>       Box(<br>           modifier = Modifier.drawWithContent {<br>               infoContentGraphicsLayer.record { this@drawWithContent.drawContent() }<br>           }<br>       ) {<br>           currentInfoContent()<br>       }<br>   }<br><br>   LaunchedEffect(*keys, currentContent, currentInfoContent) {<br>       val uiImage = withContext(Dispatchers.Main) {<br>           contentGraphicsLayer.toImageBitmap().toUIImage(density.density)<br>       }<br><br>       val infoUIImage = withContext(Dispatchers.Main) {<br>           if (infoContent != null) {<br>               infoContentGraphicsLayer.toImageBitmap().toUIImage(density.density)<br>           } else {<br>               null<br>           }<br>       }<br><br>       annotation?.let { mapView.removeAnnotation(it) }<br><br>       val reuseIdentifier = keys.joinToString()<br><br>       annotation = CommonMapAnnotation(<br>           identifier = reuseIdentifier,<br>           position = position,<br>           viewCreator = { MKAnnotationView(it, reuseIdentifier) },<br>           viewBinder = { convertView -&gt; viewBinder(convertView, uiImage, infoUIImage, anchor) }<br>       ).also { mapView.addAnnotation(it) }<br>   }<br><br>   DisposableEffect(Unit) {<br>       onDispose {<br>           annotation?.let { mapView.removeAnnotation(it) }<br>       }<br>   }<br>}</pre><p>The core challenge here is converting Compose UI content into images that MapKit can display. To achieve this, we use Compose’s GraphicsLayer API (<a href="https://developer.android.com/develop/ui/compose/graphics/draw/modifiers#composable-to-bitmap">rememberGraphicsLayer</a> is available since version 1.7.0-alpha07) to render our composable content into bitmaps. We create separate graphics layers for both the marker content and its info window, then capture their rendering output. The process works in several steps. First, we render the composable content using drawWithContent and graphicsLayer.record, redirecting the drawing commands to our graphics layers. Then we convert the resulting ImageBitmap into a UIImage that MapKit can display.</p><p>The view binding implementation handles both the marker appearance and its info window:</p><pre>private fun viewBinder(convertView: MKAnnotationView, uiImage: UIImage, infoUIImage: UIImage?, anchor: Offset) {<br>   convertView.image = uiImage<br>   convertView.centerOffset = CGPointMake(anchor.x.toDouble(), anchor.y.toDouble())<br><br>   if (infoUIImage != null) {<br>       convertView.canShowCallout = true<br>       convertView.detailCalloutAccessoryView = UIImageView().apply {<br>           image = infoUIImage<br>       }<br>   } else {<br>       convertView.canShowCallout = false<br>       convertView.detailCalloutAccessoryView = null<br>   }<br>}</pre><p>For the info window, we utilize <a href="https://developer.apple.com/documentation/mapkit/mkannotationview?language=objc#overview">MKAnnotationView</a>’s <em>selection state </em>called callout. When info window content is provided, we enable the callout and set its content using a UIImageView containing our rendered composable.</p><p>The implementation manages the marker’s lifecycle, removing old annotations before adding new ones and cleaning up when the composable leaves the composition.</p><h4>Putting It All Together: Composable Map in Action</h4><p>Now that we have our map infrastructure in place, we can create rich, interactive map experiences using pure Compose code. Let’s look at a practical example that showcases how to build a transit map application:</p><pre>MaterialTheme {<br>   Box(modifier = Modifier.fillMaxSize()) {<br>       CommonMap(<br>           modifier = Modifier.fillMaxSize(),<br>           contentPadding = PaddingValues(16.dp)<br>       ) {<br>           if (isCloseZoomLevel) {<br>               Trip(route)<br>           } else {<br>               SubwayLines()<br>           }<br>       }<br><br>       Column(<br>           modifier = Modifier.align(Alignment.BottomEnd)<br>               .padding(16.dp),<br>           verticalArrangement = Arrangement.spacedBy(2.dp)<br>       ) {<br>           ZoomButton(painterResource(Res.drawable.ic_plus)) { zoomIn() }<br>           ZoomButton(painterResource(Res.drawable.ic_minus)) { zoomOut() }<br>       }<br>   }<br>}</pre><p>This main screen demonstrates the flexibility of our map implementation. It conditionally displays either detailed trip information or the subway network based on the zoom level, while maintaining zoom controls as overlay UI elements.</p><p>For subway line visualization, we create composable functions that handle both the lines and their endpoints:</p><pre>@Composable<br>fun SubwayLines() {<br>   SubwayLine.entries.forEach { line -&gt;<br>       SubwayLineItem(line = line)<br>   }<br>}<br><br>@Composable<br>private fun SubwayLineItem(line: SubwayLine) {<br>   val points = remember(line) { line.polyline.map { it.toLatLng() }.toImmutableList() }<br><br>   Polyline(<br>       points = points,<br>       color = line.color,<br>       width = 4.dp<br>   )<br><br>   SubwayLineEndStation(<br>       position = points.first(),<br>       color = line.color<br>   )<br><br>   SubwayLineEndStation(<br>       position = points.last(),<br>       color = line.color<br>   )<br>}<br><br>@Composable<br>private fun SubwayLineEndStation(<br>   position: LatLng,<br>   color: Color<br>) {<br>   MarkerComposable(<br>       position = position,<br>       anchor = Offset(0.5f, 0.5f)<br>   ) {<br>       Box(<br>           modifier = Modifier.size(8.dp)<br>               .background(color, shape = CircleShape)<br>               .padding(2.dp)<br>               .background(Color.White, shape = CircleShape)<br>       )<br>   }<br>}</pre><p>For individual trip visualization, we create markers with info windows for start and end points:</p><pre>@Composable<br>fun Trip(route: ImmutableList&lt;LatLng&gt;) {<br>   Polyline(<br>       points = route,<br>       color = Color.Blue,<br>       width = 3.dp<br>   )<br><br>   MarkerInfoWindowComposable(<br>       position = route.first(),<br>       anchor = Offset(0.5f, 1f),<br>       infoContent = {<br>           Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {<br>               Text(&quot;Start&quot;, style = MaterialTheme.typography.headlineMedium)<br>               Text(&quot;Trip start marker&quot;, style = MaterialTheme.typography.bodyMedium)<br>           }<br>       }<br>   ) {<br>       Image(<br>           modifier = Modifier.size(24.dp),<br>           painter = painterResource(Res.drawable.map_marker_home),<br>           contentDescription = &quot;Start&quot;<br>       )<br>   }<br><br>   MarkerInfoWindowComposable(<br>       position = route.last(),<br>       anchor = Offset(0.5f, 1f),<br>       infoContent = {<br>           Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {<br>               Text(&quot;Stop&quot;, style = MaterialTheme.typography.headlineMedium)<br>               Text(&quot;Trip stop marker&quot;, style = MaterialTheme.typography.bodyMedium)<br>           }<br>       }<br>   ) {<br>       Image(<br>           modifier = Modifier.size(24.dp),<br>           painter = painterResource(Res.drawable.map_marker_check),<br>           contentDescription = &quot;Stop&quot;<br>       )<br>   }<br>}</pre><p>This example demonstrates how our map abstraction allows us to work with complex map features using familiar Compose patterns. We can create custom markers with info windows, draw routes and transit lines, and manage map state, all while maintaining a clean, declarative API that works consistently across platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*fdKMYEKfMS86tHrSoDrfzA.gif" /></figure><h4>Moving Forward</h4><p>We’ve transformed our MapKit integration into a more idiomatic Compose implementation, but this is just the beginning of what’s possible. The patterns we’ve established, from state management to custom rendering, provide a foundation for implementing additional MapKit features. Camera controls, different types of overlays, and various map interactions can all be built using similar approaches.</p><p>While our implementation handles the core functionality needed for most map-based applications, there’s room for further optimization and enhancement. You can find a basic implementation of camera handling in the <a href="https://github.com/apolacsek/kmp-compose-mapkit">GitHub repository</a>, which serves as a starting point for more advanced features. The patterns we’ve covered can be extended to implement any additional functionality your application requires, whether that’s clustering markers, adding custom overlays, or implementing complex map interactions.</p><p>I hope this guide helps you create more maintainable and flexible map implementations in your Compose Multiplatform applications. Happy coding!</p><p><em>At Supercharge, we create smart product strategies, design delightful interfaces, and build robust, AI-driven software to turn some of our partners’ most challenging digital initiatives into success stories. If you liked this article, check out some of Supercharge’s other articles on our </em><a href="https://medium.com/supercharges-mobile-product-guide"><em>blog</em></a><em>. If you’re interested in open positions, </em><a href="https://supercharge.io/careers/positions"><em>follow this link.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d498b6aef96c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/supercharges-mobile-product-guide/integrating-mapkit-in-compose-multiplatform-part-2-refining-implementation-d498b6aef96c">Integrating MapKit in Compose Multiplatform — Part 2: Refining implementation</a> was originally published in <a href="https://medium.com/supercharges-mobile-product-guide">Supercharge&#39;s Digital Product Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating MapKit in Compose Multiplatform]]></title>
            <link>https://medium.com/supercharges-mobile-product-guide/integrating-mapkit-in-compose-multiplatform-165de6141364?source=rss-c68baa516378------2</link>
            <guid isPermaLink="false">https://medium.com/p/165de6141364</guid>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[mapkit]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Attila Polacsek]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 14:21:00 GMT</pubDate>
            <atom:updated>2025-02-03T09:05:29.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMOpeVXg9LPKzLDm5o-5MQ.jpeg" /></figure><p>Compose Multiplatform enables developers to integrate native UIKit components directly into their Compose UI applications, leveraging Kotlin Multiplatform’s interoperability features. In this tutorial, we’ll explore how to embed Apple’s MapKit into a Compose application through UIKitView. We’ll specifically cover:</p><ul><li>Integrating native UIKit elements within Compose UI</li><li>Working with <a href="https://developer.apple.com/documentation/mapkit?language=objc">MapKit</a> in Kotlin to create an interactive map experience</li></ul><p>This guide assumes you’re familiar with Compose fundamentals and Kotlin Multiplatform setup. We’ll dive straight into the UIKit integration specifics and MapKit implementation, keeping our focus on the native iOS integration aspects.</p><h3>First Steps: Working with UIKitView</h3><p>Before diving into MapKit, let’s start with a simple example to understand how UIKitView works. The following snippet demonstrates the basic usage by embedding a UILabel — iOS’s native text component:</p><pre>@Composable<br>fun ComposeView(text: String) {<br>   UIKitView(<br>       modifier = Modifier.fillMaxSize(),<br>       factory = {<br>           UILabel().apply {<br>               textColor = UIColor.systemBlueColor<br>           }<br>       },<br>       update = { view -&gt;<br>           view.text = text<br>       }<br>   )<br>}</pre><p>The UIKitView composable requires two essential parameters: a factory lambda that creates the native view, and an update lambda that handles view updates. The factory block runs once when the view is created, making it ideal for initial setup like setting the text color. The update block is called whenever the composable is recomposed, allowing us to update the view’s properties based on new data — in this case, setting the label’s text.</p><p>This pattern — creating a view in factory and updating it in update — is fundamental to working with UIKitView and will be the same approach we’ll use with MapKit. Notice how we can seamlessly access native UIKit properties like textColor and text directly from Kotlin, demonstrating the power of Kotlin Multiplatform’s Objective-C interop.</p><h3>Working with MKMapView</h3><h4>Define a cross-platform API</h4><p>Now that we understand the basics of UIKitView, let’s build our map integration. We’ll start by defining a platform-agnostic API that can be used from our common code. This abstraction will allow us to keep our business logic platform-independent while providing native map implementations for both iOS and Android:</p><pre>data class Coordinate(val latitude: Double, val longitude: Double)<br><br>@Composable<br>expect fun NativeMap(<br>   centerCoordinate: Coordinate,<br>   modifier: Modifier = Modifier<br>)</pre><p>This simple API defines a Coordinate data class for handling geographical positions and a composable function NativeMap that will render our map centered on the given coordinate. In this tutorial, we’ll focus on implementing the iOS target using MapKit’s <a href="https://developer.apple.com/documentation/mapkit/mkmapview?language=objc">MKMapView</a>. For the Android implementation using Google Maps, you can refer to the complete source code in the repository.</p><p>Let’s implement our NativeMap composable for iOS using MKMapView. Following the same UIKitView pattern we explored earlier, we’ll create and configure the native map component:</p><pre>@Composable<br>actual fun NativeMap(<br>   centerCoordinate: Coordinate,<br>   modifier: Modifier<br>) {<br>   val clLocation = remember(centerCoordinate) {<br>      CLLocationCoordinate2DMake(<br>         centerCoordinate.latitude,<br>         centerCoordinate.longitude<br>      )<br>   }<br>   UIKitView(<br>       modifier = Modifier,<br>       factory = {<br>           MKMapView().apply {<br>               setZoomEnabled(true)<br>               setScrollEnabled(true)<br>               // customize map view further<br>           }<br>       },<br>       update = { mapView -&gt;<br>           mapView.setCenterCoordinate(clLocation, animated = true)<br>       }<br>   )<br>}</pre><p>Our implementation follows the same principles we saw with UILabel, but with some important additions. We use remember to memoize the creation of our <a href="https://developer.apple.com/documentation/corelocation/cllocationcoordinate2d?language=objc">CLLocationCoordinate2D</a> object, which is only recreated when the input coordinate changes. This optimization prevents unnecessary object creation during recomposition.</p><p>In the factoryblock, we create and configure our MKMapViewinstance, enabling basic map interactions like zooming and scrolling. The update block handles changes to the center coordinate, smoothly animating the map to the new position when the coordinate changes.</p><p>Notice how we can directly call native MapKit methods from Kotlin, such as setZoomEnabled and setCenterCoordinate. This seamless integration allows us to take full advantage of MapKit’s capabilities while maintaining a clean, Compose-friendly API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjWE9gPX9xHUkqOhOzzxJg.png" /></figure><h4>Enhanced Map Features: Add Marker</h4><p>Let’s enhance our map by adding markers. First, we’ll update our common API to support a marker with both location and title:</p><pre>data class Marker(<br>   val title: String,<br>   val coordinate: Coordinate<br>)<br><br>@Composable<br>expect fun NativeMap(<br>   marker: Marker,<br>   modifier: Modifier = Modifier<br>)</pre><p>Now we can implement markers on iOS using <a href="https://developer.apple.com/documentation/mapkit/mkpointannotation?language=objc">MKPointAnnotation</a>, MapKit’s native annotation system:</p><pre>val clLocation = CLLocationCoordinate2DMake(<br>   marker.coordinate.latitude,<br>   marker.coordinate.longitude<br>)<br><br>val annotation = MKPointAnnotation().apply {<br>   setTitle(marker.title)<br>   setCoordinate(clLocation)<br>}<br><br>mapView.addAnnotation(annotation)</pre><p>This creates a marker at the specified coordinate with a title that appears when the user taps it. However, we need to be careful about annotation management to avoid duplicates during recomposition. Here’s our updated implementation:</p><pre>@Composable<br>actual fun NativeMap(<br>   marker: Marker,<br>   modifier: Modifier<br>) {<br>   val clLocation = remember(marker) {<br>       CLLocationCoordinate2DMake(<br>           marker.coordinate.latitude,<br>           marker.coordinate.longitude<br>       )<br>   }<br><br>   UIKitView(<br>       modifier = modifier,<br>       factory = {<br>           MKMapView().apply {<br>               setZoomEnabled(true)<br>               setScrollEnabled(true)<br>           }<br>       },<br>       update = { mapView -&gt;<br>           // Remove existing annotations before adding new ones<br>           mapView.removeAnnotations(mapView.annotations)<br><br>           val pointAnnotation = MKPointAnnotation().apply {<br>               setTitle(marker.title)<br>               setCoordinate(clLocation)<br>           }<br>           mapView.addAnnotation(pointAnnotation)<br>           mapView.setCenterCoordinate(clLocation, animated = true)<br>       }<br>   )<br>}</pre><p>Note how we clear existing annotations before adding new ones in the update block. This prevents duplicate markers from appearing when the composable recomposes. The map will automatically center on the marker’s position and display its title.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlOwTx1r70rryUEVOZv2xQ.png" /></figure><h4>Route Visualization: Drawing Paths on the Map</h4><p>Let’s extend our map to display a route between two markers. We’ll first update our API to support start and end locations along with a list of coordinates representing the route:</p><pre>@Composable<br>expect fun NativeMap(<br>   startLocation: Marker,<br>   stopLocation: Marker,<br>   route: ImmutableList&lt;Coordinate&gt;,<br>   modifier: Modifier = Modifier<br>)</pre><p>To keep our code clean and maintainable, let’s first refactor our marker creation logic into a separate composable function:</p><pre>@Composable<br>fun rememberMarkerAnnotation(marker: Marker): MKPointAnnotation {<br>   return remember(marker) {<br>       val clLocation = CLLocationCoordinate2DMake(<br>           marker.coordinate.latitude,<br>           marker.coordinate.longitude<br>       )<br><br>       MKPointAnnotation().apply {<br>           setTitle(marker.title)<br>           setCoordinate(clLocation)<br>       }<br>   }<br>}</pre><p>This function uses rememberto cache the annotation, recreating it only when the marker data changes.</p><p>Now for the interesting part — creating the route overlay. MapKit uses <a href="https://developer.apple.com/documentation/mapkit/mkpolyline?language=objc">MKPolyline</a> to draw lines on the map, but it requires coordinates in a C-style array. Here’s how we bridge the gap between Kotlin’s collections and C arrays:</p><pre>@Composable<br>fun rememberPolyline(route: ImmutableList&lt;Coordinate&gt;): MKPolyline {<br>   return remember(route) {<br>       memScoped {<br>           // allocate a C style array to hold the coordinates<br>           val coordinates = allocArray&lt;CLLocationCoordinate2D&gt;(route.size)<br><br>           route.forEachIndexed { index, coordinate -&gt;<br>               // get the CValue of CLLocationCoordinate2D<br>               val clLocation = CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude)<br><br>               // calculate the offset of the current coordinate in the array<br>               val offset = index * sizeOf&lt;CLLocationCoordinate2D&gt;()<br><br>               // calculate the memory address of the current coordinate in the array<br>               val pointer = coordinates.rawValue + offset<br><br>               // copy the coordinate to the calculated memory address<br>               clLocation.place(interpretPointed&lt;CLLocationCoordinate2D&gt;(pointer).ptr)<br>           }<br><br>           MKPolyline.polylineWithCoordinates(<br>               coords = coordinates,<br>               count = route.size.toULong()<br>           )<br>       }<br>   }<br>}</pre><p>This code demonstrates one of the more complex aspects of Kotlin/Native: manual memory management. When working with C APIs like MapKit’s <a href="https://developer.apple.com/documentation/mapkit/mkpolyline/1452205-polylinewithcoordinates?language=objc">MKPolyline.polylineWithCoordinates</a>, we need to provide data in a format C understands — a contiguous block of memory containing our coordinates. We can’t simply pass our Kotlin collection directly; instead, we need to manage native memory carefully.</p><p>The <a href="https://kotlinlang.org/api/core/kotlin-stdlib/kotlinx.cinterop/mem-scoped.html#memscoped">memScoped</a> block creates a safe context for native memory operations. It serves as a crucial memory management tool that automatically frees all allocated memory when the scope ends, preventing potential memory leaks in the process. This automatic cleanup ensures that temporary native memory is properly managed and doesn’t persist beyond its intended lifecycle. Furthermore, the memScoped block establishes a clear, structured boundary where native memory operations can safely occur, making the code’s memory management intentions explicit and maintainable.</p><p>Inside the memScoped block, our code allocates a C array sized to hold our route coordinates, then proceeds to convert each Kotlin coordinate to a native CLLocationCoordinate2D. It calculates the correct memory position for each coordinate and places them into the array before finally creating the polyline using MapKit’s native API.</p><p>The remember function ensures we only perform this memory-intensive operation when our route data actually changes.</p><p>We can safely return the MKPolyline from our memScoped block because MapKit copies the coordinate data it needs during creation, allowing our temporary array to be freed without affecting our polyline overlay.</p><p>There are alternative approaches to manage native memory in Kotlin/Native. You can allocate memory directly on the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/native-heap/#nativeheap">NativeHeap</a> and free it manually when you’re done, or use an <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/-arena/#arena">Arena</a> which allows multiple allocations that can be freed with a single clear call. Like the MemScope used in our implementation, Arena lives on the native heap. You can find both alternative implementations in the repository for this article.</p><h4>Delegate Pattern: Customizing Map Rendering</h4><p>When we run our code, we’ll notice that only the markers appear on the map while our route overlay remains invisible. This happens because markers have a default visual implementation, but overlays require custom rendering through MapKit’s delegate system.</p><p>To customize the map’s appearance, we need to implement the <a href="https://developer.apple.com/documentation/mapkit/mkmapviewdelegate?language=objc">MKMapViewDelegate</a> protocol:</p><pre>@Composable<br>fun rememberMKMapViewDelegate(): MKMapViewDelegateProtocol {<br>   return remember {<br>       object : NSObject(), MKMapViewDelegateProtocol {<br>           // implement delegate methods<br>       }<br>   }<br>}</pre><p>We can connect this delegate to our map view in the NativeMap composable:</p><pre>// create a delegate in our NativeMap composable before the UIKitView<br>val delegate = rememberMKMapViewDelegate()<br><br>// set the delegate in the factory callback<br>mapView.setDelegate(delegate)</pre><p>To render our route overlay, we implement the rendererForOverlay method in our delegate and return an overlay renderer:</p><pre>@Suppress(&quot;CONFLICTING_OVERLOADS&quot;, &quot;PARAMETER_NAME_CHANGED_ON_OVERRIDE&quot;)<br>@ObjCSignatureOverride<br>override fun mapView(mapView: MKMapView, rendererForOverlay: MKOverlayProtocol): MKOverlayRenderer {<br>   val polyline = rendererForOverlay as? MKPolyline ?: return MKOverlayRenderer()<br><br>   val renderer = MKPolylineRenderer(overlay = polyline).apply {<br>       setStrokeColor(UIColor.systemBlueColor)<br>       setLineWidth(3.0)<br>   }<br><br>   return renderer<br>}</pre><p>Note the annotations at the top of our method. Objective-C allows overloads by selector, such functions can have the same types and differ only by parameter names in Kotlin. This is generally not supported and results in an error. Kotlin 2.0 introduced the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/-obj-c-signature-override/#objcsignatureoverride">@ObjCSignatureOverride </a>annotation to handle this use case. This annotation instructs the Kotlin compiler to use the Objective-C method overloading. Android Studio does not support this fully yet, so we need the @Suppress annotation to hide the IDE errors. The return type will be still marked as error, but we can compile and run it.</p><p>The implementation creates a blue line with a width of 3 points to represent our route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H88Y0DQ9PyWJB6Go86kfqQ.png" /></figure><h3>What’s Next?</h3><p>In this tutorial, we’ve covered the fundamentals of integrating native iOS components into your Compose Multiplatform application. We’ve learned how to bridge the gap between Compose UI and UIKit, implemented basic map functionality with markers and routes, and handled the complexities of memory management in Kotlin/Native.</p><p>However, this is just the beginning of what’s possible with MapKit integration. In the next post, we’ll explore advanced customization options, including custom markers and advanced route styling.</p><p>The complete source code for this tutorial is available on <a href="https://github.com/apolacsek/kmp-compose-mapkit">GitHub</a>, where you’ll find additional examples and alternative implementations of the concepts we’ve covered.</p><p><em>Update: You can find the follow up article here </em><a href="https://medium.com/supercharges-mobile-product-guide/integrating-mapkit-in-compose-multiplatform-part-2-refining-implementation-d498b6aef96c"><em>Integrating MapKit in Compose Multiplatform — Part 2: Refining implementation</em></a></p><p><em>At Supercharge, we create smart product strategies, design delightful interfaces, and build robust, AI-driven software to turn some of our partners’ most challenging digital initiatives into success stories. If you liked this article, check out some of Supercharge’s other articles on our </em><a href="https://medium.com/supercharges-mobile-product-guide"><em>blog</em></a><em>. If you’re interested in open positions, </em><a href="https://supercharge.io/careers/positions"><em>follow this link.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165de6141364" width="1" height="1" alt=""><hr><p><a href="https://medium.com/supercharges-mobile-product-guide/integrating-mapkit-in-compose-multiplatform-165de6141364">Integrating MapKit in Compose Multiplatform</a> was originally published in <a href="https://medium.com/supercharges-mobile-product-guide">Supercharge&#39;s Digital Product Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>