---
title: "Show nearby places on a map in a flow"
description: "Display a map of places near each user, such as partner fitness centers, in a custom element on a flow screen."
---

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/llms.txt).

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

Follow this recipe to include an interactive map in a flow. The map shows your places, such as partner fitness centers, within 2 km of the user. Your app renders the map as a native view in a [custom element](flow-custom-elements), with MapKit on iOS and with MapLibre on Android. Users grant or decline location access on the screen before the map.

## Before you start

- Update your app to Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 or later. Earlier SDK versions show the [fallback content](flow-custom-elements#set-fallback-content) for every custom element.
- Set up your app to [fetch](kmp-get-pb-paywalls) and [display](kmp-present-paywalls) flows.
- Set up the native code of your app for custom elements, as in the [Kotlin Multiplatform guide](kmp-flow-custom-elements#before-you-start).
- On iOS, the map view needs iOS 17 or later. On iOS 16, users see the fallback.
- On iOS, to ask users for location access, add the `NSLocationWhenInUseUsageDescription` key to `iosApp/iosApp/Info.plist`. Set its value to the reason for location access, such as "Find fitness centers near you." iOS shows this text in the location alert.
- On Android, add MapLibre to the `androidMain` dependencies, from the `org.maplibre.gl:android-sdk-opengl` artifact. With this artifact, Google Play also offers your app to devices without Vulkan, which the default `android-sdk` artifact requires.

## 1. Ask for location access

To tell users why your app needs their location, ask for location access on a screen before the map:

1. In the Flow & Paywall Builder, add a screen before the screen with the map. On it, add a text that explains the request, such as "Find fitness centers near you," and a **Continue** button.
2. [Add an **On Tap** trigger](onboarding-actions#set-up-interactions) with the **Request permission** action to the **Continue** button.
3. From the **Permission** dropdown, select **Location while using the app**.

The default **After response** action is **Navigate Next**, so whether users grant location access or decline it, they go to the screen with the map. Users without location access see the fallback there. To skip the screen with the map for users who decline, add the **Navigate to Screen** action to **When denied**, and select the screen after the map.

To design the screen that has the **Request permission** action, see [Add the request to a screen](flow-permissions#add-the-request-to-a-screen).

When users tap **Continue**, the Adapty SDK sends the permission request to the permission handler in your app. To show the location dialog and pass the result to the flow, add the [`requestLocationWhenInUse()` function](kmp-handle-permissions#location_when_use) to the handler.

## 2. Add the custom element to the screen

In the Flow & Paywall Builder, [add a custom element](flow-custom-elements#add-and-configure) to a flow screen, and set it up for the map:

- **Type**: `map`.
- **ID**: `fitness_centers`.
- **Height**: Keep the default **Fixed** height. The map fills the custom element.

Keep the custom element out of containers that respond to touch, such as a carousel, so that only the map responds to a drag on it.

Inside the custom element, add an [**Image**](custom-media#image) with a picture of a map. Users see it as the [fallback](flow-custom-elements#set-fallback-content) when:

- Their version of your app doesn't display the map.
- They didn't grant location access.
- Their device runs iOS 16.

## 3. Create the map view

Create a type for your places, and a model that reads location access:

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift"
import CoreLocation

// A place of your app, such as a partner fitness center
struct Place: Identifiable {
    let id = UUID()
    let name: String
    let coordinate: CLLocationCoordinate2D
}

// Reads location access for the resolver
@MainActor
final class LocationAccess {
    private let manager = CLLocationManager()

    var isAllowed: Bool {
        let status = manager.authorizationStatus
        return status == .authorizedWhenInUse || status == .authorizedAlways
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin"
import android.Manifest
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.PackageManager
import androidx.activity.ComponentActivity
import androidx.core.content.ContextCompat

// a place of your app, such as a partner fitness center
data class Place(val name: String, val latitude: Double, val longitude: Double)

private const val PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION // granted with approximate or precise location

// reads location access for the resolver
class LocationAccess(context: Context) {
    private val appContext = context.applicationContext

    val isAllowed: Boolean
        get() = ContextCompat.checkSelfPermission(appContext, PERMISSION) == PackageManager.PERMISSION_GRANTED
}

// the activity that shows the flow
tailrec fun Context.findComponentActivity(): ComponentActivity =
    this as? ComponentActivity ?: (this as ContextWrapper).baseContext.findComponentActivity()
```

</TabItem>
</Tabs>

Create a view with a map. The view displays a marker for each of your places within 2 km of the user:

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift"
import CoreLocation
import MapKit
import SwiftUI

@available(iOS 17.0, *)
struct NearbyFitnessCentersMap: View {
    let places: [Place]
    @State private var position: MapCameraPosition = .userLocation(fallback: .automatic)
    @State private var nearbyPlaces: [Place] = []

    var body: some View {
        Map(position: $position) {
            UserAnnotation()
            ForEach(nearbyPlaces) { place in
                Marker(place.name, systemImage: "dumbbell.fill", coordinate: place.coordinate)
                    .tint(.teal)
            }
        }
        .task {
            do {
                for try await update in CLLocationUpdate.liveUpdates() {
                    guard let location = update.location else { continue }
                    nearbyPlaces = places.filter { place in
                        let placeLocation = CLLocation(
                            latitude: place.coordinate.latitude,
                            longitude: place.coordinate.longitude
                        )
                        return location.distance(from: placeLocation) <= 2_000 // meters
                    }
                    withAnimation {
                        position = .automatic // zoom to fit the user and the places
                    }
                    break
                }
            } catch {
                // the map still shows the location of the user
            }
        }
    }
}
```

The map view needs iOS 17 or later. On iOS 16, users see the fallback.

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin"
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.location.Location
import android.os.Looper
import android.widget.FrameLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import org.maplibre.android.MapLibre
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.engine.LocationEngineCallback
import org.maplibre.android.location.engine.LocationEngineDefault
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.engine.LocationEngineResult
import org.maplibre.android.maps.MapView
import org.maplibre.android.style.layers.CircleLayer
import org.maplibre.android.style.layers.PropertyFactory
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.geojson.Feature
import org.maplibre.geojson.FeatureCollection
import org.maplibre.geojson.Point

// map tiles without an API key
const val MAP_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty"

class NearbyFitnessCentersMap(
    context: Context,
    private val places: List<Place>,
) : FrameLayout(context), DefaultLifecycleObserver, LocationEngineCallback<LocationEngineResult> {
    private val activity = context.findComponentActivity()
    private val locationEngine = LocationEngineDefault.getDefaultLocationEngine(context)
    private val mapView: MapView

    init {
        MapLibre.getInstance(context)
        mapView = MapView(context)
        mapView.onCreate(null)
        mapView.getMapAsync { map -> map.setStyle(MAP_STYLE_URL) }
        addView(mapView)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        activity.lifecycle.addObserver(this)
        showUser()
    }

    override fun onDetachedFromWindow() {
        locationEngine.removeLocationUpdates(this)
        activity.lifecycle.removeObserver(this)
        // the SDK creates a new view each time the custom element appears: release this map
        mapView.onPause()
        mapView.onStop()
        mapView.onDestroy()
        super.onDetachedFromWindow()
    }

    // passes the lifecycle of the activity to the map
    override fun onStart(owner: LifecycleOwner) = mapView.onStart()
    override fun onResume(owner: LifecycleOwner) = mapView.onResume()
    override fun onPause(owner: LifecycleOwner) = mapView.onPause()
    override fun onStop(owner: LifecycleOwner) = mapView.onStop()

    @SuppressLint("MissingPermission") // runs only after the user allows location access
    private fun showUser() = mapView.getMapAsync { map ->
        map.getStyle { style ->
            val options = LocationComponentActivationOptions.builder(context, style).locationEngine(locationEngine)
            map.locationComponent.activateLocationComponent(options.build())
            map.locationComponent.isLocationComponentEnabled = true
            val request = LocationEngineRequest.Builder(1_000).build() // milliseconds between updates
            locationEngine.requestLocationUpdates(request, this, Looper.getMainLooper()) // calls onSuccess
        }
    }

    // the first location of the user
    override fun onSuccess(result: LocationEngineResult) {
        val user = result.lastLocation ?: return
        locationEngine.removeLocationUpdates(this)
        showPlaces(user)
    }

    override fun onFailure(exception: Exception) = Unit

    // a teal circle for each of your places within 2 km of the user
    private fun showPlaces(user: Location) = mapView.getMapAsync { map ->
        val distance = FloatArray(1)
        val pins = places.filter { place ->
            Location.distanceBetween(user.latitude, user.longitude, place.latitude, place.longitude, distance)
            distance[0] <= 2_000 // meters
        }.map { place -> Feature.fromGeometry(Point.fromLngLat(place.longitude, place.latitude)) }
        map.getStyle { style ->
            style.addSource(GeoJsonSource("places", FeatureCollection.fromFeatures(pins)))
            val teal = PropertyFactory.circleColor(Color.rgb(0, 128, 128))
            style.addLayer(CircleLayer("pins", "places").withProperties(teal, PropertyFactory.circleRadius(8f)))
        }
        // zoom in on the area around the user
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(user.latitude, user.longitude), 12.0))
    }
}
```

The view loads the map from OpenFreeMap, a free service that needs no API key and has no uptime guarantee. To switch to another tile source, change the `MAP_STYLE_URL` constant.

</TabItem>
</Tabs>

## 4. Match the map to the custom element

In your [app-wide resolver](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk), add properties for the `LocationAccess` model and your places. Then return the map view for the `map` Type and the `fitness_centers` ID. The highlighted lines show what to add or change. If your app has no app-wide [resolver](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) yet, copy the whole code:

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift" {5-6,14-21}
import AdaptyUIBuilder
import SwiftUI

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let locationAccess = LocationAccess()
    let places: [Place] // your app's places, such as partner fitness centers

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "map" where id == "fitness_centers":
            guard #available(iOS 17.0, *) else {
                return nil // iOS 16: show the fallback
            }
            guard locationAccess.isAllowed else {
                return nil // no location access: show the fallback
            }
            return AnyView(NearbyFitnessCentersMap(places: places))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin" {7,9,13-24}
import android.content.Context
import com.adapty.ui.AdaptyCustomElementContent
import com.adapty.ui.AdaptyCustomElementsResolver

class CustomElementsResolver(
    context: Context,
    private val places: List<Place>, // your app's places, such as partner fitness centers
) : AdaptyCustomElementsResolver {
    private val locationAccess = LocationAccess(context)

    override fun resolve(type: String, id: String): AdaptyCustomElementContent? =
        when (type) {
            "map" -> when (id) {
                "fitness_centers" ->
                    if (!locationAccess.isAllowed) {
                        null // no location access: show the fallback
                    } else {
                        AdaptyCustomElementContent.view(
                            factory = { context, _ -> NearbyFitnessCentersMap(context, places) },
                        )
                    }
                // the other maps of your resolver
                else -> null
            }
            // the other Types of your resolver
            else -> null
        }
}
```

</TabItem>
</Tabs>

The SDK calls the resolver when the screen with the map opens. If the user granted location access, the resolver returns the map view. Otherwise, it returns no view, and users see the fallback. A permission change doesn't make the SDK call the resolver again, so ask for location access on the screen before the map.

Create the resolver with your places, and set it as the app-wide resolver at app launch:

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

In `iOSApp.swift`, add the imports, and set the resolver in the `application(_:didFinishLaunchingWithOptions:)` method of your `AppDelegate` class. The highlighted lines show what to add. Keep the rest of the `AppDelegate` class as it is:

```swift showLineNumbers title="iosApp/iosApp/iOSApp.swift" {1-2,10-15}
import AdaptyUI
import CoreLocation
import SwiftUI

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // your app's places, such as partner fitness centers
        let places = [
            Place(name: "Central Fitness", coordinate: CLLocationCoordinate2D(latitude: 52.5219, longitude: 13.4132)),
            Place(name: "Riverside Gym", coordinate: CLLocationCoordinate2D(latitude: 52.5163, longitude: 13.3777)),
        ]
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(places: places))
        // the rest of your launch code
        return true
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

In `MainApplication.kt`, add a property for your places, and set the resolver in the `onCreate` method. The highlighted lines show what to add. Keep the rest of the `MainApplication` class as it is:

```kotlin showLineNumbers title="MainApplication.kt" {7-11,15}
package com.example.app

import android.app.Application
import com.adapty.ui.AdaptyUI

class MainApplication : Application() {
    // your app's places, such as partner fitness centers
    val places = listOf(
        Place("Central Fitness", latitude = 52.5219, longitude = 13.4132),
        Place("Riverside Gym", latitude = 52.5163, longitude = 13.3777),
    )

    override fun onCreate() {
        super.onCreate()
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, places))
    }
}
```

</TabItem>
</Tabs>

If your shared code loads the places, send them to a store in your native code through an interface that each platform implements. For an example, see the [weight goal chart recipe](kmp-custom-element-interactive-chart), which sends the current and goal weight this way.

## 5. Test on a device

The Flow & Paywall Builder can't run your app code, so its canvas only shows the fallback. To preview the map:

1. [Publish the flow](builder-save-publish). To see the latest published version instead of a cached one, register the device as a [test device](test-devices).
2. To see a marker on the map, add a place within 2 km of your location to your list of places.
3. Run a build of your app that includes the resolver and the permission handler. On iOS, use a device with iOS 17 or later. On the screen before the map, tap **Continue**, and grant location access. Verify that the map shows your location and a marker for the place that you added.

To test the fallback, deny location access:

- **iOS**: In the **Settings** app, go to **Privacy & Security** > **Location Services** > *your app*, and select **Never**. Then open the flow again.
- **Android**: In the **Settings** app, turn off location access for your app. Then open the flow again. If Android shows the permission dialog after you tap **Continue**, deny location access.

If your flow sends users who decline past the screen with the map, verify that the flow skips this screen. If it doesn't, verify that the fallback appears on the screen with the map.

To find out why the fallback appears instead of the map, follow the instructions in the [Test on a device](kmp-flow-custom-elements#test-on-a-device) section of the Kotlin Multiplatform guide.