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

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

按照本教程，在流程中嵌入一个交互式地图。地图会显示用户 2 公里范围内的相关地点（如合作健身中心）。你的应用使用 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)流程。
- 如需向用户请求位置权限，请在继承自 `ComponentActivity` 的 Activity（例如 `AppCompatActivity`）中展示流程。
- 通过 Gradle 将 MapLibre 添加到您的应用，使用 `org.maplibre.gl:android-sdk-opengl` 依赖包。使用该依赖包后，Google Play 也会将您的应用提供给不支持 Vulkan 的设备（默认的 `android-sdk` 依赖包需要 Vulkan 支持）。
- 将 `minSdk` 设置为 23 或更高版本，因为 MapLibre 有此要求。

要将您的应用限制为近似位置，请在 `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>

创建一个带有地图的视图。该视图请求位置访问权限，并为用户 2 公里范围内的每个地点显示一个标记：

<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. 若要在地图上看到标记，请在你的地点列表中添加一个距你当前位置 2 公里以内的地点。
3. 运行包含解析器的应用构建版本，打开该页面，并允许位置访问。验证地图是否显示了你的位置以及你添加的地点标记。

要测试备用付费墙，请在 **Settings** 应用中关闭你的应用的位置访问权限。打开该界面，如果出现提示，请拒绝位置访问。地图视图将显示关于 Settings 的提示信息。再次打开该界面，确认备用付费墙已出现。

要了解为什么显示备用付费墙而不是地图，请参阅 Android 指南中[在设备上测试](android-flow-custom-elements#test-on-a-device)部分的说明。