---
title: "Flow'da yakın yerleri harita üzerinde gösterme"
description: "Bir flow ekranındaki özel öğede, ortak fitness merkezleri gibi her kullanıcıya yakın yerlerin haritasını görüntüleyin."
---

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

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

Bir flow'a etkileşimli harita eklemek için bu tarifi uygulayın. Harita, kullanıcıya 2 km yakınındaki iş ortağı fitness merkezleri gibi kendi mekânlarınızı gösterir. Uygulamanız haritayı iOS'ta MapKit, Android'de MapLibre kullanarak [custom element](flow-custom-elements) içinde native bir view olarak render eder. Kullanıcılar, harita ekranından önce gelen ekranda konum erişimine izin verir ya da reddeder.

## Başlamadan önce \{#before-you-start\}

- Uygulamanızı Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 veya sonraki bir sürüme güncelleyin. Daha eski SDK sürümleri, her özel öğe için [yedek içeriği](flow-custom-elements#set-fallback-content) gösterir.
- Uygulamanızı flow'ları [çekmek](kmp-get-pb-paywalls) ve [görüntülemek](kmp-present-paywalls) için ayarlayın.
- Uygulamanızın native kodunu özel öğeler için [Kotlin Multiplatform kılavuzundaki](kmp-flow-custom-elements#before-you-start) gibi yapılandırın.
- iOS'ta harita görünümü iOS 17 veya sonrasını gerektirir. iOS 16'da kullanıcılar yedek içeriği görür.
- iOS'ta kullanıcılardan konum erişimi istemek için `NSLocationWhenInUseUsageDescription` anahtarını `iosApp/iosApp/Info.plist` dosyasına ekleyin. Değerini "Yakınızdaki spor merkezlerini bulun." gibi konum erişiminin neden gerektiğini açıklayan bir metne ayarlayın. iOS bu metni konum uyarısında gösterir.
- Android'de `androidMain` bağımlılıklarına `org.maplibre.gl:android-sdk-opengl` artifact'ından MapLibre'yi ekleyin. Bu artifact sayesinde Google Play, varsayılan `android-sdk` artifact'ının gerektirdiği Vulkan desteği olmayan cihazlara da uygulamanızı sunar.

## 1. Konum erişimi isteyin \{#1-ask-for-location-access\}

Kullanıcılara uygulamanızın neden konumlarına ihtiyaç duyduğunu açıklamak için haritadan önceki bir ekranda konum erişimi isteyin:

1. Flow & Paywall Builder'da haritanın bulunduğu ekrandan önce bir ekran ekleyin. Bu ekranda, "Size yakın fitness merkezlerini bulun" gibi isteği açıklayan bir metin ve bir **Continue** düğmesi ekleyin.
2. **Continue** düğmesine [**On Tap** tetikleyicisi ekleyin](onboarding-actions#set-up-interactions) ve **Request permission** eylemini seçin.
3. **Permission** açılır menüsünden **Location while using the app** seçeneğini seçin.

Varsayılan **After response** eylemi **Navigate Next** olduğundan, kullanıcılar konum erişimine izin verse de vermese de haritanın bulunduğu ekrana yönlendirilir. Konum erişimi olmayan kullanıcılar orada yedek içeriği görür. İzni reddeden kullanıcılar için haritanın bulunduğu ekranı atlamak istiyorsanız **When denied** alanına **Navigate to Screen** eylemini ekleyin ve haritadan sonraki ekranı seçin.

**Request permission** eylemini içeren ekranı tasarlamak için bkz. [İsteği bir ekrana ekleme](flow-permissions#add-the-request-to-a-screen).

Kullanıcılar **Continue** düğmesine dokunduğunda, Adapty SDK izin isteğini uygulamanızdaki izin işleyicisine gönderir. Konum diyaloğunu göstermek ve sonucu flow'a iletmek için işleyiciye [`requestLocationWhenInUse()` fonksiyonunu](kmp-handle-permissions#location_when_use) ekleyin.

## 2. Özel öğeyi ekrana ekle \{#add-the-custom-element-to-the-screen\}

Flow & Paywall Builder'da, bir flow ekranına [özel bir öğe ekleyin](flow-custom-elements#add-and-configure) ve harita için ayarlayın:

- **Tür**: `map`.
- **ID**: `fitness_centers`.
- **Yükseklik**: Varsayılan **Fixed** yüksekliği koruyun. Harita, özel öğeyi doldurur.

Özel öğeyi, carousel gibi dokunuşa tepki veren container'ların içine koymayın; böylece yalnızca harita sürükleme hareketine yanıt verir.

Özel öğenin içine, harita görseli içeren bir [**Image**](custom-media#image) ekle. Kullanıcılar bunu şu durumlarda [yedek içerik](flow-custom-elements#set-fallback-content) olarak görür:

- Uygulamalarının sürümü haritayı görüntüleyemiyorsa.
- Konum erişimine izin vermedilerse.
- Cihazları iOS 16 çalıştırıyorsa.

## 3. Harita görünümünü oluşturun \{#create-the-map-view\}

Yerleriniz için bir tür oluşturun ve konum erişimini okuyan bir model yazın:

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

Kullanıcıya 2 km mesafe içindeki her konumunuz için bir işaretçi gösteren harita içeren bir görünüm oluşturun:

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

Harita görünümü iOS 17 veya sonrasını gerektirir. iOS 16'da kullanıcılar yedek paywall'ı görür.

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

Görünüm, haritayı API anahtarı gerektirmeyen ve çalışma süresi garantisi bulunmayan ücretsiz bir hizmet olan OpenFreeMap'ten yükler. Farklı bir harita kaynağına geçmek için `MAP_STYLE_URL` sabitini değiştirin.

</TabItem>
</Tabs>

## 4. Haritayı özel öğeyle eşleştirin \{#match-the-map-to-the-custom-element\}

[Uygulama genelindeki çözümleyicinizde](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk), `LocationAccess` modeli ve yerleriniz için özellikler ekleyin. Ardından `map` Türü ve `fitness_centers` kimliği için harita görünümünü döndürün. Vurgulanan satırlar neyin ekleneceğini veya değiştirileceğini gösterir. Uygulamanızda henüz uygulama genelinde bir [çözümleyici](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) yoksa, kodun tamamını kopyalayın:

<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, harita içeren ekran açıldığında resolver'ı çağırır. Kullanıcı konum erişimine izin verdiyse, resolver harita görünümünü döndürür. Aksi takdirde görünüm döndürmez ve kullanıcılar yedek içeriği görür. İzin değişikliği SDK'nın resolver'ı yeniden çağırmasını sağlamaz; bu nedenle konum erişimini harita ekranından önce gelen ekranda isteyin.

Create the resolver with your places, and set it as the app-wide resolver at app launch:

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

In `iOSApp.swift`, add the imports, and set the resolver in the `application(_:didFinishLaunchingWithOptions:)` method of your `AppDelegate` class. The highlighted lines show what to add. Keep the rest of the `AppDelegate` class as it is:

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

In `MainApplication.kt`, add a property for your places, and set the resolver in the `onCreate` method. The highlighted lines show what to add. Keep the rest of the `MainApplication` class as it is:

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

Paylaşılan kodunuz placement'ları yüklüyorsa, her platformun uyguladığı bir arayüz aracılığıyla bunları native kodunuzdaki bir store'a gönderin. Örnek için, mevcut ve hedef ağırlığı bu şekilde gönderen [ağırlık hedefi grafik tarifine](kmp-custom-element-interactive-chart) bakın.

## 5. Cihazda test etme \{#5-test-on-a-device\}

Flow & Paywall Builder, uygulama kodunuzu çalıştıramaz; bu nedenle tuval yalnızca yedek içeriği gösterir. Haritayı önizlemek için:

1. [Flow'u yayınlayın](builder-save-publish). Önbelleğe alınmış sürüm yerine en son yayınlanan sürümü görmek için cihazı [test cihazı](test-devices) olarak kaydedin.
2. Haritada bir işaretçi görmek için konumunuzun 2 km yakınına bir yer ekleyin.
3. Resolver ve izin işleyicisini içeren uygulamanızın bir build'ini çalıştırın. iOS'ta iOS 17 veya sonraki sürümü olan bir cihaz kullanın. Haritadan önceki ekranda **Continue** düğmesine dokunun ve konum erişimine izin verin. Haritanın konumunuzu ve eklediğiniz yerin işaretçisini gösterdiğini doğrulayın.

Yedeği test etmek için konum erişimini reddedin:

- **iOS**: **Ayarlar** uygulamasında **Gizlilik ve Güvenlik** > **Konum Servisleri** > *uygulamanız* yolunu izleyin ve **Hiçbir Zaman** seçeneğini seçin. Ardından flow'u tekrar açın.
- **Android**: **Ayarlar** uygulamasında uygulamanız için konum erişimini kapatın. Ardından flow'u tekrar açın. **Devam** düğmesine dokunduktan sonra Android izin iletişim kutusunu gösterirse konum erişimini reddedin.

Flow'unuz konumu reddeden kullanıcıları harita içeren ekranın ötesine geçiriyorsa, flow'un bu ekranı atladığını doğrulayın. Atlamıyorsa, harita içeren ekranda yedek içeriğin görüntülendiğini doğrulayın.

Yedek yerine haritanın neden göründüğünü öğrenmek için Kotlin Multiplatform kılavuzundaki [Cihazda test etme](kmp-flow-custom-elements#test-on-a-device) bölümündeki talimatları izleyin.