---
title: "Flow ekranında yakındaki yerleri haritada göster"
description: "Her kullanıcının yakınındaki yerleri, örneğin ortak fitness merkezlerini, bir flow ekranındaki özel öğede harita olarak gösterin."
---

> 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 izleyin. Harita, kullanıcının 2 km yakınındaki yerlerinizi (örneğin ortak fitness merkezleri) gösterir. Uygulamanız haritayı iOS'ta MapKit, Android'de MapLibre kullanarak [özel öğe](flow-custom-elements) içinde native bir görünüm olarak render eder. Uygulama, flow ekranında konum erişimi talep eder.

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

- Uygulamanızı Adapty Flutter SDK 4.4 veya sonraki bir sürüme güncelleyin. Daha önceki SDK sürümleri, her özel element için [yedek içeriği](flow-custom-elements#set-fallback-content) gösterir.
- Uygulamanızı flow'ları [getirmek](flutter-get-pb-paywalls) ve [görüntülemek](flutter-present-paywalls) için ayarlayın.
- Uygulamanızın yerel kodunu özel elementler için, [Flutter kılavuzunda](flutter-flow-custom-elements#before-you-start) açıklandığı şekilde yapılandırın.
- iOS'ta harita görünümü iOS 17 veya daha yenisini gerektirir. iOS 16'da kullanıcılar yedeği görür.
- iOS'ta kullanıcılardan konum erişimi istemek için `ios/Runner/Info.plist` dosyasına `NSLocationWhenInUseUsageDescription` anahtarını ekleyin. Değerini "Find fitness centers near you." gibi, istekte gösterilecek metin olarak ayarlayın.
- Android'de, `org.maplibre.gl:android-sdk-opengl` kaynağından Gradle ile MapLibre'yi uygulamanıza ekleyin. Bu artifact sayesinde Google Play, uygulamanızı varsayılan `android-sdk` artifact'ının gerektirdiği Vulkan'ı desteklemeyen cihazlara da sunar.
- Android'de, MapLibre'nin gerektirdiği şekilde `minSdk` değerini 23 veya daha yüksek olarak ayarlayın.

Android uygulamanızı yaklaşık konumla sınırlamak için `android/app/src/main/AndroidManifest.xml` dosyasındaki `<manifest>` öğesinin içine aşağıdakini ekleyin. `<manifest>` öğesinin `xmlns:tools="http://schemas.android.com/tools"` ifadesini bildirdiğinden emin olun.

```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. Özel öğeyi ekrana ekleyin \{#1-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, bir harita resmi içeren bir [**Görsel**](custom-media#image) ekleyin. Kullanıcılar bunu şu durumlarda [yedek](flow-custom-elements#set-fallback-content) olarak görür:

- Uygulamanızın kullandıkları sürümü haritayı görüntüleyemiyorsa.
- Ekran açılmadan önce konum erişimini reddettilerse.
- Cihazları iOS 16 çalıştırıyorsa.

Kullanıcı konum erişim iznini henüz yanıtlamamışsa, uygulama haritayı gösterdiğinde bu izni ister. Kullanıcılara uygulamanızın neden konumlarına ihtiyaç duyduğunu belirtmek için özel öğenin üzerine "Yakınındaki spor salonlarını bul." gibi bir metin öğesi ekleyin.

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

Yerleriniz için bir tür ve konum erişimi için bir model oluşturun:

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

Kullanıcının 2 km yakınındaki her konumunuz için bir işaretçi görüntüleyen ve konum erişimi talep eden bir harita içeren 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 {
    @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 }
    }
}
```

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

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

</TabItem>
</Tabs>

Kullanıcı ekranda konum erişimini reddederse, görünüm haritanın yerine Ayarlar'da erişime nasıl izin verileceğini açıklayan bir mesaj gösterir.

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

[Uygulama genelindeki resolver](flutter-flow-custom-elements#pass-the-resolver-to-the-sdk)'ınızda, `LocationAccess` modeli ve yerleriniz için özellikler ekleyin. Ardından `map` Tipi ve `fitness_centers` ID'si için harita görünümünü döndürün. Vurgulanan satırlar, neyin ekleneceğini veya değiştirileceğini göstermektedir. Uygulamanızda henüz uygulama genelinde bir [resolver](flutter-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
            }
            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, ekran açıldığında ve ekran açıkken özel öğe her yeniden çizildiğinde resolver'ı çağırır. Konum erişimi, her çağrıda resolver'ın ne döndüreceğini belirler:

- **Henüz yanıtlanmadı**: Harita görünümü; böylece görünüm erişim talep edebilir.
- **İzin verildi**: Kullanıcının yakınındaki yerlerinizi gösteren harita görünümü.
- **Ekran açılmadan önce reddedildi**: Hiçbir görünüm döndürülmez; kullanıcılar Ayarlar mesajı yerine yedek içeriği görür.
- **Ekranda reddedildi**: Harita görünümü; çünkü görünüm ekrandayken `isMapOnScreen` değerini ayarlar. Resolver burada hiçbir görünüm döndürmeseydi, SDK bir sonraki çağrıda Ayarlar mesajını yedek içerikle değiştirirdi.

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 `ios/Runner/AppDelegate.swift`, add the imports, and set the resolver in the `application(_:didFinishLaunchingWithOptions:)` method. Keep the rest of the `AppDelegate` class as it is:

```swift showLineNumbers title="ios/Runner/AppDelegate.swift"

// in application(_:didFinishLaunchingWithOptions:), before `return super.application(...)`
// 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))
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

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

    override fun onCreate() {
        super.onCreate()
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, places))
    }
}
```

`android/app/src/main/AndroidManifest.xml` dosyasındaki `App` sınıfını, [Çözümleyiciyi SDK'ya aktar](flutter-flow-custom-elements#pass-the-resolver-to-the-sdk) bölümünde açıklandığı gibi adlandırın.

</TabItem>
</Tabs>

Dart kodunuz yerleri yüklüyorsa, bunları [ağırlık hedefi grafik tarifi](flutter-custom-element-interactive-chart)'nin ağırlıklar için yaptığı gibi, yerel kodunuzun bir platform kanalı aracılığıyla doldurduğu bir depoda saklayın.

## 4. Cihazda Test Edin \{#4-test-on-a-device\}

Flow & Paywall Builder uygulama kodunuzu çalıştıramaz, bu yüzden kanvas yalnızca yedek paywall'u 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 görmek için, bulunduğunuz konuma 2 km'den yakın bir yeri yer listenize ekleyin.
3. Resolver'ı içeren uygulamanızın bir build'ini çalıştırın. iOS'ta iOS 17 veya sonraki bir sürümü olan bir cihaz kullanın. Ekranı açın ve konum erişimine izin verin. Haritanın konumunuzu ve eklediğiniz yere ait işareti gösterdiğini doğrulayın.

Yedek davranışı 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 ekranı tekrar açın.
- **Android**: **Ayarlar** uygulamasında uygulamanız için konum erişimini kapatın. Ekranı açın; izin istemi görünürse konum erişimini reddedin. Harita görünümü Ayarlar hakkında bir mesaj gösterir. Ekranı tekrar açın ve yedek içeriğin göründüğünü doğrulayın.

Harita yerine neden yedek içeriğin göründüğünü öğrenmek için Flutter kılavuzunun [Cihazda test etme](flutter-flow-custom-elements#test-on-a-device) bölümündeki talimatları izleyin.