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

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

このレシピに従って、フローにインタラクティブなマップを組み込みましょう。マップには、パートナーのフィットネスセンターなど、ユーザーの半径2km以内にある場所が表示されます。アプリはMapLibreを使って、[カスタム要素](flow-custom-elements)としてマップをネイティブビューでレンダリングします。フロースクリーンで位置情報へのアクセス許可をリクエストします。

## 始める前に \{#before-you-start\}

- アプリを Adapty Android SDK 4.4 以降にアップデートしてください。それより古い SDK バージョンでは、すべてのカスタム要素に[フォールバックコンテンツ](flow-custom-elements#set-fallback-content)が表示されます。
- アプリにフローの[取得](android-get-pb-paywalls)と[表示](android-present-paywalls)を設定してください。
- ユーザーに位置情報へのアクセスを求めるには、`AppCompatActivity` などの `ComponentActivity` を継承したアクティビティでフローを表示してください。
- Gradle を使って `org.maplibre.gl:android-sdk-opengl` から MapLibre をアプリに追加してください。このアーティファクトを使用すると、デフォルトの `android-sdk` アーティファクトが必要とする Vulkan 非対応デバイスにも Google Play がアプリを提供できます。
- MapLibre の要件に合わせて `minSdk` を 23 以上に設定してください。

アプリをおおよその位置情報のみに制限するには、`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)として表示されます：

- ユーザーのアプリバージョンが地図を表示できない場合。
- スクリーンが開く前に位置情報のアクセスを拒否した場合。

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

## 2. マップビューを作成する \{#2-create-the-map-view\}

場所の型と、位置情報アクセス用のモデルを作成します。

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```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>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

// a place of your app, such as a partner fitness center
public class Place {
    public final String name;
    public final double latitude;
    public final double longitude;

    public Place(String name, double latitude, double longitude) {
        this.name = name;
        this.latitude = latitude;
        this.longitude = longitude;
    }
}

// one location access model for the resolver and the map view
public class LocationAccess {
    private static final String PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION; // approximate location
    private final Context appContext;
    // checkSelfPermission returns the same value before the first request and after a denial: save the answer
    private final SharedPreferences answers;
    private boolean isAsking;
    public boolean isMapOnScreen;

    public LocationAccess(Context context) {
        appContext = context.getApplicationContext();
        answers = appContext.getSharedPreferences("location_access", Context.MODE_PRIVATE);
    }

    public boolean isAllowed() {
        return ContextCompat.checkSelfPermission(appContext, PERMISSION) == PackageManager.PERMISSION_GRANTED;
    }

    public boolean isDenied() {
        return !isAllowed() && answers.getBoolean("denied", false);
    }

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

    // the activity that shows the flow
    public static ComponentActivity findComponentActivity(Context context) {
        while (!(context instanceof ComponentActivity)) {
            context = ((ContextWrapper) context).getBaseContext();
        }
        return (ComponentActivity) context;
    }
}
```

</TabItem>
</Tabs>

マップ付きのビューを作成します。このビューは位置情報へのアクセスを要求し、ユーザーの半径2km以内にある各プレイスのマーカーを表示します：

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```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>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

public class NearbyFitnessCentersMap extends FrameLayout
        implements DefaultLifecycleObserver, LocationEngineCallback<LocationEngineResult> {
    // map tiles without an API key
    public static final String MAP_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty";

    private final LocationAccess access;
    private final List<Place> places;
    private final ComponentActivity activity = LocationAccess.findComponentActivity(getContext());
    private final LocationEngine locationEngine =
            LocationEngineDefault.INSTANCE.getDefaultLocationEngine(getContext());
    private final MapView mapView;
    private ActivityResultLauncher<String> permissionRequest;

    public NearbyFitnessCentersMap(Context context, LocationAccess access, List<Place> places) {
        super(context);
        this.access = access;
        this.places = places;
        MapLibre.getInstance(context);
        mapView = new MapView(context);
        mapView.onCreate(null);
        mapView.getMapAsync(map -> map.setStyle(MAP_STYLE_URL));
        addView(mapView);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        access.isMapOnScreen = true; // tells the resolver that the map is on the screen
        activity.getLifecycle().addObserver(this);
        if (access.isAllowed()) showUser();
        else if (access.isDenied()) showAccessOff();
        else permissionRequest = access.requestAccess(activity, granted -> {
            if (granted) showUser(); else showAccessOff();
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        access.isMapOnScreen = false;
        if (permissionRequest != null) permissionRequest.unregister();
        locationEngine.removeLocationUpdates(this);
        activity.getLifecycle().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 public void onStart(LifecycleOwner owner) { mapView.onStart(); }
    @Override public void onResume(LifecycleOwner owner) { mapView.onResume(); }
    @Override public void onPause(LifecycleOwner owner) { mapView.onPause(); }
    @Override public void onStop(LifecycleOwner owner) { mapView.onStop(); }

    @SuppressLint("MissingPermission") // runs only after the user allows location access
    private void showUser() {
        mapView.getMapAsync(map -> map.getStyle(style -> {
            map.getLocationComponent().activateLocationComponent(
                    LocationComponentActivationOptions.builder(getContext(), style).locationEngine(locationEngine).build());
            map.getLocationComponent().setLocationComponentEnabled(true);
            LocationEngineRequest request = new LocationEngineRequest.Builder(1000).build(); // milliseconds between updates
            locationEngine.requestLocationUpdates(request, this, Looper.getMainLooper()); // calls onSuccess
        }));
    }

    // the first location of the user
    @Override
    public void onSuccess(LocationEngineResult result) {
        Location user = result.getLastLocation();
        if (user == null) return;
        locationEngine.removeLocationUpdates(this);
        showPlaces(user);
    }

    @Override public void onFailure(Exception exception) {}

    // a teal circle for each of your places within 2 km of the user
    private void showPlaces(Location user) {
        List<Feature> pins = new ArrayList<>();
        float[] distance = new float[1];
        for (Place place : places) {
            Location.distanceBetween(user.getLatitude(), user.getLongitude(), place.latitude, place.longitude, distance);
            if (distance[0] > 2000) continue; // meters
            pins.add(Feature.fromGeometry(Point.fromLngLat(place.longitude, place.latitude)));
        }
        mapView.getMapAsync(map -> map.getStyle(style -> {
            style.addSource(new GeoJsonSource("places", FeatureCollection.fromFeatures(pins)));
            style.addLayer(new CircleLayer("pins", "places").withProperties(
                    PropertyFactory.circleColor(Color.rgb(0, 128, 128)), PropertyFactory.circleRadius(8f)));
            // zoom in on the area around the user
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(user.getLatitude(), user.getLongitude()), 12));
        }));
    }

    private void showAccessOff() {
        mapView.setVisibility(GONE);
        TextView message = new TextView(getContext());
        message.setText("Location access is off. To see fitness centers near you, allow location access in Settings.");
        message.setGravity(Gravity.CENTER);
        addView(message);
    }
}
```

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

</TabItem>
</Tabs>

ユーザーが画面で位置情報へのアクセスを拒否した場合、ビューはマップの代わりに、設定でアクセスを許可する方法についてのメッセージを表示します。

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

[アプリ全体のリゾルバー](android-flow-custom-elements#display-views-in-every-flow)に、`LocationAccess` モデルとプレイスのプロパティを追加します。次に、`map` タイプと `fitness_centers` ID に対してマップビューを返します。ハイライトされた行が追加・変更する箇所です。アプリにまだアプリ全体の[リゾルバー](android-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views)がない場合は、コード全体をコピーしてください。

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```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>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java" {7-8,10-12,17-28}

public class CustomElementsResolver implements AdaptyCustomElementsResolver {
    private final LocationAccess locationAccess;
    private final List<Place> places; // your app's places, such as partner fitness centers

    public CustomElementsResolver(Context context, List<Place> places) {
        this.locationAccess = new LocationAccess(context);
        this.places = places;
    }

    @Override
    public AdaptyCustomElementContent resolve(String type, String id) {
        if (type.equals("map")) {
            if (id.equals("fitness_centers")) {
                if (locationAccess.isDenied() && !locationAccess.isMapOnScreen) {
                    return null; // access denied before the screen opened: show the fallback
                }
                return AdaptyCustomElementContent.view(
                        (context, elementContext) -> new NearbyFitnessCentersMap(context, locationAccess, places)
                );
            }
            // the other maps of your resolver
            return null;
        }
        // the other Types of your resolver
        return null;
    }
}
```

</TabItem>
</Tabs>

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

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

リゾルバーをプレースごとに作成し、アプリ全体のリゾルバーとして設定します。`AdaptyUI.setCustomElementsResolver` はアプリ起動時など、一度だけ呼び出してください。

<Tabs groupId="current-os" queryString>
<TabItem value="kotlin" label="Kotlin" default>

```kotlin showLineNumbers title="Kotlin"

class App : 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),
    )

    // keep this instance: a resolver for one flow can reuse it
    // lazy: the context isn't attached yet while App is constructed
    val customElementsResolver by lazy { CustomElementsResolver(this, places) }

    override fun onCreate() {
        super.onCreate()
        AdaptyUI.setCustomElementsResolver(customElementsResolver)
    }
}
```

</TabItem>
<TabItem value="java" label="Java">

```java showLineNumbers title="Java"

public class App extends Application {
    // your app's places, such as partner fitness centers
    private final List<Place> places = Arrays.asList(
            new Place("Central Fitness", 52.5219, 13.4132),
            new Place("Riverside Gym", 52.5163, 13.3777)
    );
    // keep this instance: a resolver for one flow can reuse it
    private CustomElementsResolver customElementsResolver;

    @Override
    public void onCreate() {
        super.onCreate();
        customElementsResolver = new CustomElementsResolver(this, places);
        AdaptyUI.setCustomElementsResolver(customElementsResolver);
    }

    public CustomElementsResolver getCustomElementsResolver() {
        return customElementsResolver;
    }
}
```

</TabItem>
</Tabs>

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

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

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

フォールバックをテストするには、**設定**アプリでアプリの位置情報アクセスをオフにします。画面を開いて許可を求めるプロンプトが表示されたら、拒否してください。マップビューに設定に関するメッセージが表示されます。もう一度画面を開いて、フォールバックが表示されることを確認してください。

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