---
title: "フロー内で近隣の場所をマップに表示する"
description: "カスタム要素を使って、フロー画面上にユーザーの近くにある場所（提携フィットネスセンターなど）のマップを表示します。"
---

> **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 React Native SDK 4.4 以降にアプリを更新してください。それより古いバージョンのSDKでは、すべてのカスタム要素に[フォールバックコンテンツ](flow-custom-elements#set-fallback-content)が表示されます。
- フローを[取得](react-native-get-pb-paywalls)および[表示](react-native-present-paywalls)するようにアプリをセットアップしてください。
- [React Native ガイド](react-native-flow-custom-elements#before-you-start)に従って、カスタム要素用のアプリのネイティブコードをセットアップしてください。
- iOS では、マップビューに iOS 17 以降が必要です。iOS 16 ではフォールバックが表示されます。
- iOS で位置情報へのアクセスをユーザーに求めるには、`NSLocationWhenInUseUsageDescription` キーを `ios/YourApp/Info.plist` に追加してください。値には「近くのフィットネスセンターを探す」などのプロンプトテキストを設定してください。
- Android では、`org.maplibre.gl:android-sdk-opengl` から Gradle を使って MapLibre をアプリに追加してください。このアーティファクトを使用すると、デフォルトの `android-sdk` アーティファクトが必要とする Vulkan 非搭載デバイスにも Google Play からアプリが提供されます。
- Android では、MapLibre の要件に合わせて `minSdk` を 23 以上に設定してください。

Android アプリをおおよその位置情報のみに制限するには、`android/app/src/main/AndroidManifest.xml` の `<manifest>` 要素内に以下を追加してください。`<manifest>` 要素に `xmlns:tools="http://schemas.android.com/tools"` が宣言されていることを確認してください。

```xml showLineNumbers title="AndroidManifest.xml"
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- removes precise location, which MapLibre declares -->
<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION"
    tools:node="remove" />
```

## 1. カスタム要素をスクリーンに追加する \{#1-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 で動作している場合。

ユーザーがまだ位置情報アクセスのプロンプトに回答していない場合、マップが表示されるときにそのプロンプトが表示されます。アプリが位置情報を必要とする理由をユーザーに伝えるには、カスタム要素の上にテキスト要素を追加してください（例：「あなたの近くのフィットネスセンターを探す」）。

## 2. マップビューを作成する \{#2-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
}

// One location manager for the resolver and the map view
@MainActor
final class LocationAccess: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published private(set) var status: CLAuthorizationStatus = .notDetermined
    var isMapOnScreen = false
    private let manager = CLLocationManager()

    var isDenied: Bool { status == .denied || status == .restricted }

    override init() {
        super.init()
        manager.delegate = self
        status = manager.authorizationStatus
    }

    // Shows the prompt only if the user hasn't answered it yet
    func requestAccess() {
        manager.requestWhenInUseAuthorization()
    }

    nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let status = manager.authorizationStatus
        Task { @MainActor in self.status = status }
    }
}
```

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

// one location access model for the resolver and the map view
class LocationAccess(context: Context) {
    private val appContext = context.applicationContext
    // checkSelfPermission returns the same value before the first request and after a denial: save the answer
    private val answers = appContext.getSharedPreferences("location_access", Context.MODE_PRIVATE)
    private var isAsking = false
    var isMapOnScreen = false

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

    val isDenied: Boolean
        get() = !isAllowed && answers.getBoolean("denied", false)

    // requests location access and saves the answer
    // unregister the returned launcher when the view leaves the screen
    fun requestAccess(activity: ComponentActivity, onAnswer: (Boolean) -> Unit): ActivityResultLauncher<String> {
        val isPromptOpen = isAsking // after a screen rotation, this request receives the answer from the open prompt
        val request = activity.activityResultRegistry.register("location_access", RequestPermission()) { granted ->
            isAsking = false
            answers.edit().putBoolean("denied", !granted).apply()
            onAnswer(granted)
        }
        if (!isPromptOpen) {
            isAsking = true
            request.launch(PERMISSION)
        }
        return request
    }
}

// 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 {
    @ObservedObject var access: LocationAccess
    let places: [Place]
    @State private var position: MapCameraPosition = .userLocation(fallback: .automatic)
    @State private var nearbyPlaces: [Place] = []

    var body: some View {
        ZStack {
            if access.isDenied {
                ContentUnavailableView(
                    "Location access is off",
                    systemImage: "location.slash",
                    description: Text("To see fitness centers near you, allow location access in Settings.")
                )
            } else {
                Map(position: $position) {
                    UserAnnotation()
                    ForEach(nearbyPlaces) { place in
                        Marker(place.name, systemImage: "dumbbell.fill", coordinate: place.coordinate)
                            .tint(.teal)
                    }
                }
                .task {
                    access.requestAccess()
                    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
                    }
                }
            }
        }
        // Tells the resolver that the map is on the screen
        .onAppear { access.isMapOnScreen = true }
        .onDisappear { access.isMapOnScreen = false }
    }
}
```

マップビューには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 access: LocationAccess,
    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
    private var permissionRequest: ActivityResultLauncher<String>? = null

    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()
        access.isMapOnScreen = true // tells the resolver that the map is on the screen
        activity.lifecycle.addObserver(this)
        when {
            access.isAllowed -> showUser()
            access.isDenied -> showAccessOff()
            else -> permissionRequest = access.requestAccess(activity) { granted ->
                if (granted) showUser() else showAccessOff()
            }
        }
    }

    override fun onDetachedFromWindow() {
        access.isMapOnScreen = false
        permissionRequest?.unregister()
        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))
    }

    private fun showAccessOff() {
        mapView.visibility = GONE
        addView(TextView(context).apply {
            text = "Location access is off. To see fitness centers near you, allow location access in Settings."
            gravity = Gravity.CENTER
        })
    }
}
```

ビューはOpenFreeMap（APIキー不要の無料サービスで、稼働保証なし）からマップを読み込みます。別のタイルソースに切り替えるには、`MAP_STYLE_URL` 定数を変更してください。

</TabItem>
</Tabs>

ユーザーが画面で位置情報へのアクセスを拒否した場合、ビューはマップをSettings（設定）でのアクセス許可方法を説明するメッセージに置き換えます。

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

[アプリ全体のリゾルバー](react-native-flow-custom-elements#pass-the-resolver-to-the-sdk)に、`LocationAccess` モデルとその場所のプロパティを追加します。次に、`map` タイプと `fitness_centers` ID に対してマップビューを返すようにします。ハイライト行が追加・変更箇所です。アプリにまだアプリ全体の[リゾルバー](react-native-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
            }
            if locationAccess.isDenied, !locationAccess.isMapOnScreen {
                return nil // access denied before the screen opened: show the fallback
            }
            return AnyView(NearbyFitnessCentersMap(access: locationAccess, 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.isDenied && !locationAccess.isMapOnScreen) {
                        null // access denied before the screen opened: show the fallback
                    } else {
                        AdaptyCustomElementContent.view(
                            factory = { context, _ -> NearbyFitnessCentersMap(context, locationAccess, places) },
                        )
                    }
                // the other maps of your resolver
                else -> null
            }
            // the other Types of your resolver
            else -> null
        }
}
```

</TabItem>
</Tabs>

SDKは、画面が開いたときとカスタム要素が再描画されるたびにリゾルバーを呼び出します。位置情報へのアクセス状態によって、各呼び出し時にリゾルバーが返す内容が変わります：

- **未回答**: 地図ビューを返し、ビューがアクセスをリクエストできるようにします。
- **許可済み**: 地図ビューを返し、ユーザーの近くにある場所を表示します。
- **画面が開く前に拒否済み**: ビューを返さず、設定に関するメッセージの代わりにフォールバックが表示されます。
- **画面上で拒否**: 地図ビューを返します。ビューが画面上に表示されている間は `isMapOnScreen` を設定するためです。ここでリゾルバーがビューを返さなかった場合、SDKは次の呼び出し時に設定に関するメッセージをフォールバックに置き換えてしまいます。

リゾルバーをプレースと共に作成し、アプリ起動時にアプリ全体のリゾルバーとして設定します：

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

`AppDelegate.swift` にインポートを追加し、`application(_:didFinishLaunchingWithOptions:)` メソッドでリゾルバーを設定します。ハイライトされた行が追加箇所です。`AppDelegate` クラスの残りの部分はそのままにしてください：

```swift showLineNumbers title="ios/YourApp/AppDelegate.swift" {1-2,11-16}

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> 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" {1,4-8,14}

class MainApplication : Application(), ReactApplication {
  // 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),
  )

  // the other members of your MainApplication class

  override fun onCreate() {
    super.onCreate()
    AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, places))
    // the rest of your onCreate code
  }
}
```

</TabItem>
</Tabs>

JavaScriptコードでプレースを読み込む場合は、[体重目標チャートのレシピ](react-native-custom-element-interactive-chart)が体重データに対して行っているように、Turbo Native Moduleを通じてネイティブコードが書き込むストアに保持してください。

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

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

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

フォールバックをテストするには、位置情報へのアクセスを拒否してください：

- **iOS**: **設定**アプリで、**プライバシーとセキュリティ** > **位置情報サービス** > *お使いのアプリ*と進み、**なし**を選択します。その後、画面を再度開きます。
- **Android**: **設定**アプリで、アプリの位置情報アクセスをオフにします。画面を開き、プロンプトが表示された場合は位置情報アクセスを拒否します。マップビューに設定に関するメッセージが表示されます。画面を再度開き、フォールバックが表示されることを確認します。

フォールバックがマップの代わりに表示される理由を調べるには、React Native ガイドの[デバイスでテストする](react-native-flow-custom-elements#test-on-a-device)セクションの手順に従ってください。