Mapbox Android Patterns

作者 mapboxaab3a6fef5c6無授權條款收錄於 2026年10月8日更新於 2026年10月8日

Official integration patterns for Mapbox Maps SDK on Android. Covers installation, adding markers, user location, custom data, styles, camera control, and featureset interactions. Based on official Mapbox documentation.

AI 產生的概覽

在 Android 應用中整合 Mapbox Maps SDK v11 的參考模式,涵蓋 Kotlin、Jetpack Compose 與 View 體系。

功能
提供 Mapbox Maps SDK v11 在 Android 上的整合指引與程式碼模式,涵蓋安裝、存取權杖與資訊清單設定、地圖初始化、標記與註記、使用者位置顯示、自訂 GeoJSON 資料、樣式、相機控制以及要素互動。也包含效能實務與疑難排解步驟。參考檔案提供 Compose、註記、位置追蹤、自訂資料、相機與樣式、互動等更詳細的模式。
適用情境
適用於開發或維護內嵌 Mapbox 地圖的 Android 應用,且需要具體設定或使用模式時。也適合加入標記、顯示使用者位置、載入自訂資料或處理地圖點擊與手勢。
執行需求
Android SDK 21+、Kotlin 或 Java、Android Studio,以及具備存取權杖的 Mapbox 帳號。應用程式需要 Mapbox Maven 儲存庫、com.mapbox.maps:android 相依套件(Compose 另需 maps-compose)以及 INTERNET 權限;定位功能還需要位置權限。僅為說明文件,不含指令碼。

Mapbox Android Integration Patterns

Official patterns for integrating Mapbox Maps SDK v11 on Android with Kotlin, Jetpack Compose, and View system.

Use this skill when:

  • Installing and configuring Mapbox Maps SDK for Android
  • Adding markers and annotations to maps
  • Showing user location and tracking with camera
  • Adding custom data (GeoJSON) to maps
  • Working with map styles, camera, or user interaction
  • Handling feature interactions and taps

Official Resources:


Installation & Setup

Requirements

  • Android SDK 21+
  • Kotlin or Java
  • Android Studio
  • Free Mapbox account

Step 1: Configure Access Token

Create app/res/values/mapbox_access_token.xml:

xml
<?xml version="1.0" encoding="utf-8"?><resources xmlns:tools="http://schemas.android.com/tools">    <string name="mapbox_access_token" translatable="false"        tools:ignore="UnusedResources">YOUR_MAPBOX_ACCESS_TOKEN</string></resources>

Get your token: Sign in at mapbox.com

Step 1b: Internet permission (required)

Maps need network access. Include this in AndroidManifest.xml — agents often omit it and only list location permissions later:

xml
<uses-permission android:name="android.permission.INTERNET" />

Step 2: Add Maven Repository

In settings.gradle.kts:

kotlin
dependencyResolutionManagement {    repositories {        google()        mavenCentral()        maven {            url = uri("https://api.mapbox.com/downloads/v2/releases/maven")        }    }}

Step 3: Add Dependency

In module build.gradle.kts:

kotlin
android {    defaultConfig {        minSdk = 21    }}
dependencies {    implementation("com.mapbox.maps:android:11.18.1")}

For Jetpack Compose:

kotlin
dependencies {    implementation("com.mapbox.maps:android:11.18.1")    implementation("com.mapbox.extension:maps-compose:11.18.1")}

Map Initialization

Jetpack Compose Pattern

Basic map:

kotlin
import androidx.compose.runtime.*import androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.ui.Modifierimport com.mapbox.maps.extension.compose.*import com.mapbox.maps.Styleimport com.mapbox.geojson.Point
@Composablefun MapScreen() {    MapboxMap(        modifier = Modifier.fillMaxSize()    ) {        // Initialize camera via MapEffect (Style.STANDARD loads by default)        MapEffect(Unit) { mapView ->            // Set initial camera position            mapView.mapboxMap.setCamera(                CameraOptions.Builder()                    .center(Point.fromLngLat(-122.4194, 37.7749))                    .zoom(12.0)                    .build()            )        }    }}

With ornaments:

kotlin
MapboxMap(    modifier = Modifier.fillMaxSize(),    scaleBar = {        ScaleBar(            enabled = true,            position = Alignment.BottomStart        )    },    compass = {        Compass(enabled = true)    }) {    // Style.STANDARD loads by default}

View System Pattern

Layout XML (activity_map.xml):

xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">
    <com.mapbox.maps.MapView        android:id="@+id/mapView"        android:layout_width="match_parent"        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Activity:

kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport com.mapbox.maps.MapViewimport com.mapbox.maps.Styleimport com.mapbox.geojson.Point
class MapActivity : AppCompatActivity() {    private lateinit var mapView: MapView
    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_map)
        mapView = findViewById(R.id.mapView)
        mapView.mapboxMap.setCamera(            CameraOptions.Builder()                .center(Point.fromLngLat(-122.4194, 37.7749))                .zoom(12.0)                .build()        )
        mapView.mapboxMap.loadStyle(Style.STANDARD)    }
    override fun onStart() {        super.onStart()        mapView.onStart()    }
    override fun onStop() {        super.onStop()        mapView.onStop()    }
    override fun onDestroy() {        super.onDestroy()        mapView.onDestroy()    }}

Add Markers (Point Annotations)

Point annotations are the most common way to mark locations on the map.

Jetpack Compose:

kotlin
MapboxMap(modifier = Modifier.fillMaxSize()) {    MapEffect(Unit) { mapView ->        // Load style first        mapView.mapboxMap.loadStyle(Style.STANDARD)
        // Create annotation manager and add markers        val annotationManager = mapView.annotations.createPointAnnotationManager()        val pointAnnotation = PointAnnotationOptions()            .withPoint(Point.fromLngLat(-122.4194, 37.7749))            .withIconImage("custom-marker")        annotationManager.create(pointAnnotation)    }}
// Note: Compose doesn't have declarative PointAnnotation component// Markers must be added imperatively via MapEffect

View System:

kotlin
// Create annotation manager (once, reuse for updates)val pointAnnotationManager = mapView.annotations.createPointAnnotationManager()
// Create markerval pointAnnotation = PointAnnotationOptions()    .withPoint(Point.fromLngLat(-122.4194, 37.7749))    .withIconImage("custom-marker")
pointAnnotationManager.create(pointAnnotation)

Multiple markers:

kotlin
val locations = listOf(    Point.fromLngLat(-122.4194, 37.7749),    Point.fromLngLat(-122.4094, 37.7849),    Point.fromLngLat(-122.4294, 37.7649))
val annotations = locations.map { point ->    PointAnnotationOptions()        .withPoint(point)        .withIconImage("marker")}
pointAnnotationManager.create(annotations)

Show User Location (Display)

Step 1: Add permissions to AndroidManifest.xml:

xml
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Step 2: Request permissions and show location:

kotlin
// Request permissions first (use ActivityResultContracts)
// Show location puckmapView.location.updateSettings {    enabled = true    puckBearingEnabled = true}

Performance Best Practices

Reuse Annotation Managers

kotlin
// Don't create new managers repeatedly// val manager = mapView.annotations.createPointAnnotationManager() // each call
// Create once, reuseval pointAnnotationManager = mapView.annotations.createPointAnnotationManager()
fun updateMarkers() {    pointAnnotationManager.deleteAll()    pointAnnotationManager.create(markers)}

Batch Annotation Updates

kotlin
// Create all at oncepointAnnotationManager.create(allAnnotations)
// Don't create one by one in a loop

Lifecycle Management

kotlin
// Always call lifecycle methodsoverride fun onStart() {    super.onStart()    mapView.onStart()}
override fun onStop() {    super.onStop()    mapView.onStop()}
override fun onDestroy() {    super.onDestroy()    mapView.onDestroy()}

Use Standard Style

kotlin
// Standard style is optimized and recommendedStyle.STANDARD
// Use other styles only when needed for specific use casesStyle.STANDARD_SATELLITE // Satellite imagery

Troubleshooting

Map Not Displaying

Check:

  1. Token in mapbox_access_token.xml
  2. Token is valid (test at mapbox.com)
  3. Maven repository configured
  4. Dependency added correctly
  5. Internet permission in manifest

Style Not Loading

kotlin
mapView.mapboxMap.subscribeStyleLoaded { _ ->    Log.d("Map", "Style loaded successfully")    // Add layers and sources here}

Performance Issues

  • Use Style.STANDARD (recommended and optimized)
  • Limit visible annotations to viewport
  • Reuse annotation managers
  • Avoid frequent style reloads
  • Call lifecycle methods (onStart, onStop, onDestroy)
  • Batch annotation updates

Reference Files

Load these references when you need detailed patterns for specific topics:

  • references/compose.md -- Jetpack Compose: dependencies, token setup, MapboxMap, annotations with click, GeoJSON, MapEffect
  • references/annotations.md -- Circle, Polyline, and Polygon annotation patterns
  • references/location-tracking.md -- Camera follow user location + get current location once
  • references/custom-data.md -- GeoJSON sources and layers: lines, polygons, points, update/remove
  • references/camera-styles.md -- Camera control (set, animate, fit) + map styles (built-in and custom)
  • references/interactions.md -- Featureset interactions, custom layer taps, long press, gestures

Additional Resources

來源與署名

來源:mapbox/mapbox-agent-skills位於skills/mapbox-android-patterns提交aab3a6f

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架