---
title: "フロー内のマップに近くのスポットを表示する"
description: "カスタム要素を使って、フロースクリーン上にパートナーのフィットネスセンターなど、各ユーザーの近くにあるスポットのマップを表示します。"
---

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

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

この手順に従って、フローにインタラクティブマップを組み込みましょう。マップにはユーザーの近辺（半径2km以内）にある拠点（提携フィットネスセンターなど）が表示されます。アプリは[カスタム要素](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` の依存関係に追加してください。このアーティファクトを使用すると、デフォルトの `android-sdk` アーティファクトが要求する Vulkan を搭載していないデバイスにも Google Play でアプリが提供されるようになります。

## 1. 位置情報アクセスをリクエストする \{#1-ask-for-location-access\}

アプリが位置情報を必要とする理由をユーザーに伝えるには、マップが表示される画面の前に、位置情報へのアクセスを求める画面を追加します。

1. フローとペイウォールビルダーで、マップが表示される画面の前に新しい画面を追加します。そこに「近くのフィットネスセンターを探す」などの説明テキストと**Continue**ボタンを配置します。
2. **Continue**ボタンに、**Request permission**アクションを持つ[**On Tap**トリガーを追加します](onboarding-actions#set-up-interactions)。
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)として表示されます：

- アプリのバージョンが地図表示に対応していない場合。
- 位置情報へのアクセス許可が付与されていない場合。
- デバイスが 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>

ユーザーの2km以内にある各場所のマーカーを表示するマップ付きのビューを作成します：

<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から読み込まれます。OpenFreeMapは無料のサービスで、APIキーは不要ですが、稼働時間の保証はありません。別のタイルソースに切り替えるには、`MAP_STYLE_URL` 定数を変更してください。

</TabItem>
</Tabs>

## 4. マップをカスタム要素に対応させる \{#4-match-the-map-to-the-custom-element\}

[アプリ全体のリゾルバー](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk)に、`LocationAccess` モデルとプレイス用のプロパティを追加します。次に、`map` タイプと `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` に import を追加し、`AppDelegate` クラスの `application(_:didFinishLaunchingWithOptions:)` メソッドでリゾルバーを設定します。ハイライトされた行が追加箇所です。それ以外の `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)">

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

共有コードでプレースメントを読み込む場合は、各プラットフォームが実装するインターフェースを通じて、ネイティブコードのストアに送信してください。例については、[体重目標チャートのレシピ](kmp-custom-element-interactive-chart)を参照してください。このレシピでは、現在の体重と目標体重をこの方法で送信しています。

## 5. デバイスでテストする \{#5-test-on-a-device\}

フロービルダー・ペイウォールビルダーはアプリのコードを実行できないため、キャンバスにはフォールバックのみ表示されます。マップをプレビューするには:

1. [フローを公開します](builder-save-publish)。キャッシュではなく最新の公開バージョンを確認するには、デバイスを[テストデバイス](test-devices)として登録してください。
2. マップにマーカーを表示するには、現在地から2km以内の場所をプレースリストに追加してください。
3. リゾルバーとパーミッションハンドラーを含むアプリのビルドを実行します。iOS の場合は iOS 17 以降のデバイスを使用してください。マップの前の画面で **Continue** をタップして位置情報へのアクセスを許可し、マップに現在地と追加した場所のマーカーが表示されることを確認してください。

フォールバックをテストするには、位置情報へのアクセスを拒否します:

- **iOS**: **設定**アプリで**プライバシーとセキュリティ** > **位置情報サービス** > *お使いのアプリ*と進み、**なし**を選択します。その後、フローを再度開いてください。
- **Android**: **設定**アプリでお使いのアプリの位置情報へのアクセスをオフにします。その後、フローを再度開いてください。**続ける**をタップした後にAndroidが権限ダイアログを表示した場合は、位置情報へのアクセスを拒否してください。

フローが位置情報を拒否したユーザーを地図のある画面を飛ばして次に進める場合は、その画面がスキップされることを確認してください。スキップされない場合は、地図のある画面にフォールバックが表示されることを確認してください。

フォールバックが地図の代わりに表示される理由を確認するには、Kotlin Multiplatformガイドの[デバイスでテストする](kmp-flow-custom-elements#test-on-a-device)セクションの手順に従ってください。