---
title: "在流程中显示地图附近地点"
description: "在流程屏幕的自定义元素中，展示每位用户附近的地点（如合作健身中心）地图。"
---

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

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

按照此方案在流程中添加一个交互式地图。地图会显示用户 2 公里范围内的您的场所（如合作健身中心）。应用通过[自定义元素](flow-custom-elements)将地图作为原生视图渲染——iOS 使用 MapKit，Android 使用 MapLibre。用户在进入地图页面之前，需在上一个页面授予或拒绝位置权限。

## 开始之前 \{#before-you-start\}

- 将您的应用更新至 Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 或更高版本。旧版 SDK 会为每个自定义元素显示[备用内容](flow-custom-elements#set-fallback-content)。
- 配置您的应用以[获取](kmp-get-pb-paywalls)和[展示](kmp-present-paywalls)流程。
- 按照 [Kotlin Multiplatform 指南](kmp-flow-custom-elements#before-you-start)，在应用的原生代码中设置自定义元素。
- 在 iOS 上，地图视图需要 iOS 17 或更高版本。在 iOS 16 上，用户将看到备用内容。
- 在 iOS 上，若要请求用户的位置访问权限，请将 `NSLocationWhenInUseUsageDescription` 键添加到 `iosApp/iosApp/Info.plist`，并将其值设置为请求位置访问的原因，例如"查找附近的健身中心。"iOS 会在位置提示弹窗中显示此文本。
- 在 Android 上，请从 `org.maplibre.gl:android-sdk-opengl` 制品将 MapLibre 添加到 `androidMain` 依赖项中。使用此制品后，Google Play 也会将您的应用提供给不支持 Vulkan 的设备，而默认的 `android-sdk` 制品则需要 Vulkan 支持。

## 1. 请求位置访问权限 \{#1-ask-for-location-access\}

要向用户说明应用为何需要他们的位置信息，请在地图屏幕之前添加一个请求位置权限的屏幕：

1. 在 Flow & Paywall Builder 中，在包含地图的屏幕之前添加一个屏幕。在该屏幕上，添加一段说明文字，例如"查找附近的健身中心"，并添加一个 **Continue** 按钮。
2. 为 **Continue** 按钮[添加 **On Tap** 触发器](onboarding-actions#set-up-interactions)，并选择 **Request permission** 操作。
3. 在 **Permission** 下拉菜单中，选择 **Location while using the app**。

默认的 **After response** 操作为 **Navigate Next**，因此无论用户是授予还是拒绝位置权限，都会跳转到包含地图的屏幕。拒绝授权的用户在该屏幕上会看到备用内容。若要让拒绝授权的用户跳过地图屏幕，请在 **When denied** 中添加 **Navigate to Screen** 操作，并选择地图之后的屏幕。

要了解如何设计包含 **Request permission** 操作的屏幕，请参阅[将请求添加到屏幕](flow-permissions#add-the-request-to-a-screen)。

当用户点击 **Continue** 时，Adapty SDK 会将权限请求发送到应用中的权限处理器。若要显示位置对话框并将结果传递给流程，请在处理器中添加 [`requestLocationWhenInUse()` 函数](kmp-handle-permissions#location_when_use)。

## 2. 将自定义元素添加到页面 \{#2-add-the-custom-element-to-the-screen\}

在流程与付费墙编辑工具中，向流程屏幕[添加自定义元素](flow-custom-elements#add-and-configure)，并为地图进行如下设置：

- **Type**：`map`。
- **ID**：`fitness_centers`。
- **Height**：保持默认的 **Fixed** 高度。地图将填充整个自定义元素。

请勿将自定义元素放入响应触摸的容器（如轮播图）中，这样只有地图本身会响应拖拽操作。

在自定义元素中，添加一个显示地图图片的 [**Image**](custom-media#image)。在以下情况下，用户会看到它作为[备用内容](flow-custom-elements#set-fallback-content)：

- 用户使用的 app 版本不支持显示地图。
- 用户未授予位置访问权限。
- 用户的设备运行的是 iOS 16。

## 3. 创建地图视图 \{#3-create-the-map-view\}

创建一个地点类型，以及一个读取位置权限的模型：

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

```swift showLineNumbers title="Swift"

// 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"

// 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>

创建一个带有地图的视图。该视图会在用户 2 公里范围内的每个地点显示一个标记：

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

```swift showLineNumbers title="Swift"

@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
            }
        }
    }
}
```

地图视图需要 iOS 17 或更高版本。在 iOS 16 上，用户会看到备用付费墙。

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

```kotlin showLineNumbers title="Kotlin"

// 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))
    }
}
```

该视图从 OpenFreeMap 加载地图，这是一项无需 API 密钥、也不提供可用性保障的免费服务。如需切换到其他地图瓦片源，请修改 `MAP_STYLE_URL` 常量。

</TabItem>
</Tabs>

## 4. 将地图与自定义元素关联 \{#match-the-map-to-the-custom-element\}

在你的[全局解析器](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk)中，为 `LocationAccess` 模型和你的地点添加属性。然后为 `map` Type 和 `fitness_centers` ID 返回地图视图。高亮行表示需要添加或修改的内容。如果你的应用还没有全局[解析器](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views)，可以复制完整代码：

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

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

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}

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>

当包含地图的屏幕打开时，SDK 会调用解析器。如果用户已授予位置权限，解析器将返回地图视图；否则不返回任何视图，用户将看到备用内容。权限变更不会触发 SDK 再次调用解析器，因此请在地图屏幕之前的屏幕上申请位置权限。

创建包含自定义元素的解析器，并在应用启动时将其设置为全局解析器：

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

在 `iOSApp.swift` 中，添加所需的导入语句，并在 `AppDelegate` 类的 `application(_:didFinishLaunchingWithOptions:)` 方法中设置解析器。高亮行为需要添加的内容，其余部分保持不变：

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

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)">

在 `MainApplication.kt` 中，为你的版位添加一个属性，并在 `onCreate` 方法中设置解析器。高亮行显示了需要添加的内容。`MainApplication` 类的其余部分保持不变：

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

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>

如果您的共享代码负责加载版位，请通过各平台各自实现的接口，将版位传递给原生代码中的 store。具体示例可参考[体重目标数据图表示例](kmp-custom-element-interactive-chart)，该示例即采用此方式传递当前体重与目标体重。

## 5. 在设备上测试 \{#5-test-on-a-device\}

流程与付费墙编辑工具无法运行你的应用代码，因此其画布只显示备用内容。要预览地图：

1. [发布流程](builder-save-publish)。若要查看最新发布版本而非缓存版本，请将设备注册为[测试设备](test-devices)。
2. 若要在地图上看到标记，请在你的位置 2 公里范围内添加一个地点到你的地点列表。
3. 运行包含解析器和权限处理程序的应用构建版本。在 iOS 上，请使用运行 iOS 17 或更高版本的设备。在地图前的页面上，点击 **Continue**，并授予位置访问权限。确认地图显示了你的位置以及你添加的地点标记。

如需测试备用付费墙，请拒绝位置访问：

- **iOS**：在**设置**应用中，依次进入**隐私与安全性** > **定位服务** > *你的应用*，选择**永不**。然后重新打开流程。
- **Android**：在**设置**应用中，关闭你的应用的位置访问权限。然后重新打开流程。如果 Android 在你点击**继续**后弹出权限对话框，请拒绝位置访问。

如果你的流程会将拒绝权限的用户引导至地图页面之后，请验证流程是否跳过了该页面。如果没有跳过，请验证地图页面上是否显示了备用内容。

要了解为什么出现备用付费墙而不是地图，请按照 Kotlin Multiplatform 指南中[在设备上测试](kmp-flow-custom-elements#test-on-a-device)部分的说明进行操作。