---
title: "Hiển thị các địa điểm gần đây trên bản đồ trong một flow"
description: "Hiển thị bản đồ các địa điểm gần người dùng, chẳng hạn như các trung tâm thể dục đối tác, trong một phần tử tùy chỉnh trên màn hình flow."
---

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

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

Làm theo hướng dẫn này để thêm bản đồ tương tác vào một flow. Bản đồ hiển thị các địa điểm của bạn, chẳng hạn như các trung tâm thể dục liên kết, trong phạm vi 2 km quanh người dùng. App của bạn render bản đồ dưới dạng native view trong một [custom element](flow-custom-elements), sử dụng MapKit trên iOS và MapLibre trên Android. Người dùng cấp hoặc từ chối quyền truy cập vị trí ở màn hình trước bản đồ.

## Trước khi bắt đầu \{#before-you-start\}

- Cập nhật ứng dụng của bạn lên Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 hoặc mới hơn. Các phiên bản SDK cũ hơn sẽ hiển thị [nội dung dự phòng](flow-custom-elements#set-fallback-content) cho mọi thành phần tùy chỉnh.
- Thiết lập ứng dụng để [tải](kmp-get-pb-paywalls) và [hiển thị](kmp-present-paywalls) flow.
- Thiết lập code native của ứng dụng cho các thành phần tùy chỉnh, như trong [hướng dẫn Kotlin Multiplatform](kmp-flow-custom-elements#before-you-start).
- Trên iOS, chế độ xem bản đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng sẽ thấy nội dung dự phòng.
- Trên iOS, để yêu cầu người dùng cấp quyền truy cập vị trí, hãy thêm key `NSLocationWhenInUseUsageDescription` vào `iosApp/iosApp/Info.plist`. Đặt giá trị của nó là lý do truy cập vị trí, ví dụ: "Find fitness centers near you." iOS sẽ hiển thị văn bản này trong hộp thoại xin quyền vị trí.
- Trên Android, thêm MapLibre vào dependencies của `androidMain`, từ artifact `org.maplibre.gl:android-sdk-opengl`. Với artifact này, Google Play cũng sẽ cung cấp ứng dụng của bạn cho các thiết bị không có Vulkan — điều mà artifact mặc định `android-sdk` yêu cầu.

## 1. Yêu cầu quyền truy cập vị trí \{#1-ask-for-location-access\}

Để cho người dùng biết tại sao ứng dụng cần vị trí của họ, hãy yêu cầu quyền truy cập vị trí trên một màn hình trước khi hiển thị bản đồ:

1. Trong Flow & Paywall Builder, thêm một màn hình trước màn hình có bản đồ. Trên đó, thêm một đoạn văn bản giải thích yêu cầu, chẳng hạn như "Tìm trung tâm thể dục gần bạn," và một nút **Continue**.
2. [Thêm trigger **On Tap**](onboarding-actions#set-up-interactions) với hành động **Request permission** vào nút **Continue**.
3. Từ menu thả xuống **Permission**, chọn **Location while using the app**.

Hành động mặc định của **After response** là **Navigate Next**, vì vậy dù người dùng cấp hay từ chối quyền truy cập vị trí, họ đều được chuyển đến màn hình có bản đồ. Người dùng không có quyền truy cập vị trí sẽ thấy nội dung dự phòng ở đó. Để bỏ qua màn hình có bản đồ đối với những người dùng từ chối, hãy thêm hành động **Navigate to Screen** vào **When denied**, và chọn màn hình phía sau bản đồ.

Để thiết kế màn hình có hành động **Request permission**, xem [Thêm yêu cầu vào một màn hình](flow-permissions#add-the-request-to-a-screen).

Khi người dùng nhấn **Continue**, SDK Adapty sẽ gửi yêu cầu quyền đến permission handler trong ứng dụng của bạn. Để hiển thị hộp thoại vị trí và truyền kết quả vào flow, hãy thêm [hàm `requestLocationWhenInUse()`](kmp-handle-permissions#location_when_use) vào handler.

## 2. Thêm phần tử tùy chỉnh vào màn hình \{#2-add-the-custom-element-to-the-screen\}

Trong Flow & Paywall Builder, [thêm một phần tử tùy chỉnh](flow-custom-elements#add-and-configure) vào màn hình flow và cấu hình cho bản đồ:

- **Type**: `map`.
- **ID**: `fitness_centers`.
- **Height**: Giữ nguyên chiều cao mặc định **Fixed**. Bản đồ sẽ lấp đầy phần tử tùy chỉnh.

Đặt phần tử tùy chỉnh ngoài các container phản hồi thao tác chạm, chẳng hạn như carousel, để chỉ bản đồ phản hồi khi người dùng kéo trên nó.

Bên trong phần tử tùy chỉnh, thêm một [**Image**](custom-media#image) với hình ảnh bản đồ. Người dùng sẽ thấy ảnh này như nội dung [dự phòng](flow-custom-elements#set-fallback-content) khi:

- Phiên bản ứng dụng của họ không hiển thị được bản đồ.
- Họ chưa cấp quyền truy cập vị trí.
- Thiết bị của họ chạy iOS 16.

## 3. Tạo map view \{#3-create-the-map-view\}

Tạo một kiểu dữ liệu cho các địa điểm và một model đọc quyền truy cập vị trí:

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

Tạo một view có bản đồ. View này hiển thị một marker cho mỗi địa điểm của bạn trong vòng 2 km tính từ vị trí người dùng:

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

Chế độ xem bản đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng sẽ thấy paywall dự phòng.

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

Giao diện tải bản đồ từ OpenFreeMap, một dịch vụ miễn phí không cần API key và không đảm bảo uptime. Để chuyển sang nguồn tile khác, hãy thay đổi hằng số `MAP_STYLE_URL`.

</TabItem>
</Tabs>

## 4. Khớp map với custom element \{#4-match-the-map-to-the-custom-element\}

Trong [resolver toàn ứng dụng](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk) của bạn, hãy thêm các thuộc tính cho model `LocationAccess` và các địa điểm của bạn. Sau đó trả về map view cho Type `map` và ID `fitness_centers`. Các dòng được tô sáng cho thấy những gì cần thêm hoặc thay đổi. Nếu ứng dụng của bạn chưa có [resolver](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) toàn ứng dụng, hãy sao chép toàn bộ đoạn code:

<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 gọi resolver khi màn hình có bản đồ mở ra. Nếu người dùng đã cấp quyền truy cập vị trí, resolver trả về map view. Nếu không, nó không trả về view nào và người dùng sẽ thấy fallback. Việc thay đổi quyền không khiến SDK gọi lại resolver, vì vậy hãy yêu cầu quyền truy cập vị trí ở màn hình trước màn hình bản đồ.

Tạo resolver với các places của bạn, và đặt nó làm resolver toàn ứng dụng khi khởi động:

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

Trong `iOSApp.swift`, thêm các import và đặt resolver trong phương thức `application(_:didFinishLaunchingWithOptions:)` của class `AppDelegate`. Các dòng được tô sáng cho thấy những gì cần thêm. Giữ nguyên phần còn lại của class `AppDelegate`:

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

Trong `MainApplication.kt`, thêm một thuộc tính cho các placement của bạn và đặt resolver trong phương thức `onCreate`. Các dòng được highlight cho thấy những gì cần thêm. Giữ nguyên phần còn lại của class `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>

Nếu mã dùng chung của bạn tải các placement, hãy gửi chúng đến một store trong mã native thông qua một interface mà mỗi nền tảng triển khai. Để xem ví dụ, hãy tham khảo [hướng dẫn biểu đồ mục tiêu cân nặng](kmp-custom-element-interactive-chart), trong đó dữ liệu cân nặng hiện tại và mục tiêu được gửi theo cách này.

## 5. Kiểm tra trên thiết bị \{#5-test-on-a-device\}

Flow & Paywall Builder không thể chạy mã ứng dụng của bạn, vì vậy canvas chỉ hiển thị fallback. Để xem trước bản đồ:

1. [Xuất bản flow](builder-save-publish). Để xem phiên bản đã xuất bản mới nhất thay vì phiên bản được lưu trong bộ nhớ đệm, hãy đăng ký thiết bị làm [thiết bị kiểm thử](test-devices).
2. Để xem điểm đánh dấu trên bản đồ, hãy thêm một địa điểm trong phạm vi 2 km so với vị trí của bạn vào danh sách địa điểm.
3. Chạy bản build ứng dụng có bao gồm resolver và trình xử lý quyền. Trên iOS, sử dụng thiết bị chạy iOS 17 trở lên. Trên màn hình trước bản đồ, nhấn **Continue** và cấp quyền truy cập vị trí. Xác nhận rằng bản đồ hiển thị vị trí của bạn và điểm đánh dấu cho địa điểm bạn đã thêm.

Để kiểm tra phương án dự phòng, hãy từ chối quyền truy cập vị trí:

- **iOS**: Trong ứng dụng **Settings**, vào **Privacy & Security** > **Location Services** > *ứng dụng của bạn*, rồi chọn **Never**. Sau đó mở lại flow.
- **Android**: Trong ứng dụng **Settings**, tắt quyền truy cập vị trí cho ứng dụng của bạn. Sau đó mở lại flow. Nếu Android hiển thị hộp thoại xin quyền sau khi bạn nhấn **Continue**, hãy từ chối quyền truy cập vị trí.

Nếu flow của bạn chuyển hướng người dùng từ chối quyền vượt qua màn hình có bản đồ, hãy xác minh rằng flow bỏ qua màn hình này. Nếu không, hãy xác minh rằng paywall dự phòng xuất hiện trên màn hình có bản đồ.

Để tìm hiểu lý do tại sao paywall dự phòng xuất hiện thay vì bản đồ, hãy làm theo hướng dẫn trong phần [Kiểm tra trên thiết bị](kmp-flow-custom-elements#test-on-a-device) của hướng dẫn Kotlin Multiplatform.