Android集成MapBox地圖 實現(xiàn)“當(dāng)前定位”,“移動地圖獲取具體坐標(biāo)”,“坐標(biāo)轉(zhuǎn)位置 逆地址解析”,“周邊POI”

1.注冊MapBox,創(chuàng)建新令牌,獲取私密令牌并記錄保存
私密令牌只在創(chuàng)建成功后出現(xiàn)一次
私密令牌只在創(chuàng)建成功后出現(xiàn)一次
私密令牌只在創(chuàng)建成功后出現(xiàn)一次


1709018971803.jpg

2.在AndroidStudio中 ,配置私密令牌,打開項目文件gradle.properties ——>添加 MAPBOX_DOWNLOADS_TOKEN=你的私密令牌 或者打開文件?USER_HOME?/.gradle/gradle.properties。


image.png

3.配置公共令牌,創(chuàng)建文件app/src/main/res/values/developer-config.xml


image.png
  1. 聲明 Mapbox 遠(yuǎn)程存儲庫,依賴項

maven {
url 'https://api.mapbox.com/downloads/v2/releases/maven'
authentication { basic(BasicAuthentication) }
credentials {
username = "mapbox"
password = providers.gradleProperty("MAPBOX_DOWNLOADS_TOKEN").get() }
}
注意:獲取的名稱就是第二步配置的私密令牌名稱

app模塊級 build.gradle中 添加依賴
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.6.2"
implementation "com.mapbox.maps:android:10.16.4"
implementation "com.mapbox.search:mapbox-search-android-ui:1.0.0-rc.6"

  1. 具體使用 直接上代碼
//TODO 地圖定位
private fun initMapView() {
    val mode = AppCompatDelegate.getDefaultNightMode()
     //使用的是 公共令牌 第三步創(chuàng)建的
    searchEngine = SearchEngine.createSearchEngineWithBuiltInDataProviders(
        SearchEngineSettings(getString(R.string.mapbox_access_token))
    )
    var customStyleFilePath = "mapbox://styles/" //使用自己定義的主題
    val currentLanguage = Locale.getDefault().language
    if (currentLanguage == "en") {
        customStyleFilePath = if (mode == AppCompatDelegate.MODE_NIGHT_YES) {
          //英文暗色I(xiàn)D 使用自己定義的主題
             "mapbox://styles/"
        } else {
              //英文亮色I(xiàn)D 使用自己定義的主題
            "mapbox://styles/"
        }
    } else if (currentLanguage == "zh") {
        customStyleFilePath = if (mode == AppCompatDelegate.MODE_NIGHT_YES) {
            "mapbox://styles/"
            //中文暗色I(xiàn)D
        } else {
            "mapbox://styles/"
            //中文亮色I(xiàn)D
        }
    }
    //設(shè)置自定義地圖樣式
    mMapView.getMapboxMap().loadStyleUri(customStyleFilePath)

    //添加定位圖層 圖標(biāo)固定居中
    val crosshair = ImageView(requireContext())
    crosshair.layoutParams = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.WRAP_CONTENT,
        FrameLayout.LayoutParams.WRAP_CONTENT,
        Gravity.CENTER
    )
    crosshair.setImageResource(R.mipmap.icon_binding_point)
    mMapView.addView(crosshair)

    if (oldLatLng != null) {
        //如果有坐標(biāo)使用坐標(biāo)定位
        mMapView.getMapboxMap().setCamera(CameraOptions.Builder().center(oldLatLng).zoom(15.0).build()) //地圖相機(jī) 放大 到15級別
        val oldPoint = Point.fromLngLat(oldLatLng!!.longitude(), oldLatLng!!.latitude())
       //根據(jù)坐標(biāo)加載位置
        findAddress(oldPoint)
    } else {
        //沒有坐標(biāo)就獲取 當(dāng)前用戶位置 進(jìn)行定位
        mMapView.location.updateSettings {
            //打開用戶位置在地圖上可見
            enabled = true
        }
        mMapView.location.addOnIndicatorPositionChangedListener(object :
            OnIndicatorPositionChangedListener {
            override fun onIndicatorPositionChanged(point: Point) {
                mMapView.getMapboxMap().setCamera(
                    CameraOptions.Builder().center(point).zoom(14.0).build()
                )
                findAddress(point)
                mMapView.location.removeOnIndicatorPositionChangedListener(this)
                //定位完成后清除用戶位置可見
                mMapView.location.updateSettings {
                    enabled = false
                }
            }
        })
    }
    //添加地圖移動監(jiān)聽
    mMapView.getMapboxMap().addOnMoveListener(moveListener())
}

//地圖移動監(jiān)聽
private fun moveListener() = object : OnMoveListener {
    //在執(zhí)行移動手勢時調(diào)用@如果手勢被處理,則返回true,否則返回false 不處理
    override fun onMove(detector: MoveGestureDetector): Boolean {
        return false
    }
    override fun onMoveBegin(detector: MoveGestureDetector) {
    //在開始移動手勢時調(diào)用。不處理
    }
    override fun onMoveEnd(detector: MoveGestureDetector) { 
        //在移動手勢結(jié)束時調(diào)用  獲取地圖中心點(diǎn) 即是圖標(biāo)指向
        val pointCenter = mMapView.getMapboxMap().cameraState.center
        findAddress(pointCenter)
    }
}

private fun findAddress(point: Point) {
    //類型poi  獲取5條數(shù)據(jù)
    val listA = ArrayList<QueryType>()
    listA.add(QueryType.POI)
    val options = ReverseGeoOptions(
        center = Point.fromLngLat(point.longitude(), point.latitude()), limit = 5, types = listA
    )
    searchRequestTask = searchEngine.search(options, searchCallback)
}
  private val searchCallback = object : SearchCallback {
    override fun onError(e: Exception) {
        Log.i("SearchApiExample", "Reverse geocoding error", e)
    }
 override fun onResults(
          results: List<com.mapbox.search.result.SearchResult>, responseInfo:       ResponseInfo
      ) {
            if (results.isEmpty()) {
                // results 即是poi列表
            }
        }
    }
  }

定位思路:地圖布局中添加中心圖標(biāo),監(jiān)聽移動地圖,停止后獲取地圖中心的坐標(biāo)點(diǎn)進(jìn)行逆地址解析
效果圖:


image.png

個人寫法,希望對大家有幫助,不喜勿噴。歡迎交流好的方法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容