作者:Angki
轉(zhuǎn)載請(qǐng)注明
MapBox接入
MapBox的官方文檔地址枕扫,插件地址三妈。
大概的接入步驟(按照文檔來(lái)就行):
注冊(cè)MapBox賬號(hào)畜埋,創(chuàng)建私密訪問(wèn)令牌(為啥要?jiǎng)?chuàng)建呢,后面會(huì)說(shuō))畴蒲。
-
模塊級(jí)的build.gradle文件添加:
dependencies { implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:9.3.0' }
-
添加私密令牌:
在gradle.properties文件中添加 MAPBOX_DOWNLOADS_TOKEN = 私密令牌
-
項(xiàng)目級(jí)的build.gradle文件添加:
maven { url 'https://api.mapbox.com/downloads/v2/releases/maven' authentication { basic(BasicAuthentication) } credentials { username = 'mapbox' // Use the secret token you stored in gradle.properties as the password password = project.properties['MAPBOX_DOWNLOADS_TOKEN'] ?: "" } }
-
添加公共令牌:
打開R.strings.xml文件 添加 <string name="mapbox_access_token">公共令牌</string>
-
在清單文件中配置權(quán)限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
-
初始化Mapbox悠鞍,建議在Application中:
Mapbox.getInstance(this, resources.getString(R.string.mapbox_access_token))
MapBox的使用
-
布局文件中添加MapBox
<com.mapbox.mapboxsdk.maps.MapView android:id="@+id/Activity_Main_Map" android:layout_width="match_parent" android:layout_height="match_parent" mapbox:mapbox_cameraZoom="12"/> mapbox:mapbox_cameraZoom表示初始化的縮放等級(jí)
-
添加生命周期方法
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Activity_Main_Map.onCreate(savedInstanceState) } override fun onStart() { super.onStart() Activity_Main_Map.onStart() } override fun onResume() { super.onResume() Activity_Main_Map.onResume() } override fun onPause() { super.onPause() Activity_Main_Map.onPause() } override fun onStop() { super.onStop() Activity_Main_Map.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) Activity_Main_Map.onSaveInstanceState(outState) } override fun onLowMemory() { super.onLowMemory() Activity_Main_Map.onLowMemory() } override fun onDestroy() { super.onDestroy() Activity_Main_Map.onDestroy() }
-
設(shè)置地圖相關(guān)設(shè)置,在Activity_Main_Map.onCreate(savedInstanceState)后加入:
Activity_Main_Map.getMapAsync{ mapboxMap -> mapboxMap.setStyle(Style.OUTDOORS) { style -> //個(gè)性化設(shè)置 val uiSettings = mapboxMap.uiSettings //設(shè)置羅盤 uiSettings.setCompassMargins(0, AutoSizeUtils.mm2px(this, 120f), AutoSizeUtils.mm2px(this, 40f), 0) //設(shè)置本地化(需要添加本地化插件: implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-localization-v9:0.12.0') val localizationPlugin = LocalizationPlugin(Activity_Main_Map, mapboxMap, style) //將地圖與設(shè)備語(yǔ)言匹配 localizationPlugin.setMapLanguage(MapLocale.SIMPLIFIED_CHINESE) // 設(shè)置位置 // 自定義位置的顯示 val customLocationComponentOptions = LocationComponentOptions.builder(this) .trackingGesturesManagement(true) .accuracyColor(ContextCompat.getColor(this, R.color.mapboxGreen)) .build() val locationComponentActivationOptions = LocationComponentActivationOptions .builder(this, style) .locationComponentOptions(customLocationComponentOptions) .useDefaultLocationEngine(true) .build() this.mLocationComponent = mapboxMap.locationComponent // Get an instance of the LocationComponent and then adjust its settings // 獲取LocationComponent的實(shí)例模燥,然后調(diào)整其設(shè)置 this.mLocationComponent.apply { // Activate the LocationComponent with options // 使用選項(xiàng)激活LocationComponent activateLocationComponent(locationComponentActivationOptions) // Enable to make the LocationComponent visible // 啟用以使LocationComponent可見(jiàn) isLocationComponentEnabled = true // Set the LocationComponent's camera mode // 設(shè)置LocationComponent的攝像頭模式 cameraMode = CameraMode.TRACKING_COMPASS // Set the LocationComponent's render mode // 設(shè)置LocationComponent的渲染模式 renderMode = RenderMode.COMPASS } }
一些其他操作
-
將地圖源替換為天地圖的源
1.先創(chuàng)建天地圖賬號(hào)咖祭,獲取token 2.在assets文件中創(chuàng)建一個(gè)json文件: { "version": 8, "sources": { //矢量底圖源 "URL_VECTOR_2000": { "tiles": ["http://t0.tianditu.gov.cn/vec_w/wmts?tk=你的token&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles"], "type": "raster", "tileSize": 256 }, //矢量注記源 "URL_VECTOR_ANNOTATION_CHINESE_2000": { "tiles": ["http://t0.tianditu.gov.cn/cva_w/DataServer?T=cva_w&X={x}&Y={y}&L={z}&tk=你的token"], "type": "raster", "tileSize": 256 } }, "layers": [ { "id": "URL_VECTOR_2000", "type": "raster", "source": "URL_VECTOR_2000", "maxzoom": 22 }, { "id": "URL_VECTOR_ANNOTATION_CHINESE_2000", "type": "raster", "source": "URL_VECTOR_ANNOTATION_CHINESE_2000", "maxzoom": 22 } ] } 3.設(shè)置MapBox的Style: mMapBoxMap.setStyle(Style.Builder().fromUri("asset://Json文件"))
-
創(chuàng)建一個(gè)Marker(標(biāo)記點(diǎn))
//所有的標(biāo)注,建筑等等都是添加到Layer里面 mMapBoxMap.getStyle { if (it.getLayer("Home_Layer") != null) { return@getStyle } //添加icon it.addImage("marker_icon", BitmapFactory.decodeResource(resources, R.drawable.red_marker)) //設(shè)置數(shù)據(jù)(GeoJson數(shù)據(jù)) it.addSource(getMarkerSource()) //添加圖層 it.addLayer(SymbolLayer("Home_Layer", "Home") //設(shè)置屬性 .withProperties( PropertyFactory.iconImage("marker_icon"), //如果為true蔫骂,則即使其他符號(hào)與圖標(biāo)碰撞也可以看到么翰。(機(jī)翻,大概就這意思) PropertyFactory.iconIgnorePlacement(true), //如果為true辽旋,則即使該圖標(biāo)與其他先前繪制的符號(hào)發(fā)生沖突也將是可見(jiàn)的浩嫌。(機(jī)翻,大概就這意思) PropertyFactory.iconAllowOverlap(true) )) } /** * 指定坐標(biāo)數(shù)據(jù) */ fun getMarkerSource(): GeoJsonSource { val lat = 25.02365687211753 val lng = 102.73601658370522 //構(gòu)建了一個(gè)點(diǎn)的數(shù)據(jù) return GeoJsonSource("Home", Feature.fromGeometry(Point.fromLngLat(lng, lat))) }
-
設(shè)置點(diǎn)擊事件(比如給Marker設(shè)置一個(gè)點(diǎn)擊后移動(dòng)到該Marker位置的事件)
//設(shè)置點(diǎn)擊事件 mMapBoxMap.addOnMapClickListener(this) override fun onMapClick(point: LatLng): Boolean { return handleClickIcon(mMapBoxMap.projection.toScreenLocation(point)) } /** * 處理點(diǎn)擊事件 * 大概邏輯就是补胚,當(dāng)點(diǎn)擊地圖某個(gè)點(diǎn)時(shí)码耐,檢索有沒(méi)有符合的Feature,有的話處理返回false */ private fun handleClickIcon(screenPoint: PointF): Boolean { val features: List<Feature> = mMapBoxMap.queryRenderedFeatures( screenPoint, "Home_Layer" ) return if (features.isNotEmpty()) { features[0].geometry()?.let { if (it.type() == "Point") { val point = it as Point movePosition(LatLng(point.latitude(), point.longitude()), 18.0, 180.0, 30.0) } } true } else { false } }
一些問(wèn)題
-
地圖加載不出來(lái)咋辦溶其?
//使用這個(gè)方法骚腥,地圖加載失敗的提示 Activity_Main_Map.addOnDidFailLoadingMapListener { LogUtils.eTag("Angki", it) }
-
經(jīng)緯度不對(duì)?
MapBox默認(rèn)使用的WGS84坐標(biāo)系握联,而國(guó)內(nèi)使用的是GCJ-02桦沉。所以在把地圖源替換為天地圖源后坐標(biāo)會(huì)偏移〗鹈觯可以使用MapBox提供的中國(guó)插件纯露,把MapView替換為ChinaMapView。就是這個(gè)插件需要特殊的令牌代芜,估計(jì)是要購(gòu)買埠褪。
-
總結(jié)下?
MapBox官方文檔齊全挤庇,但是就不要看國(guó)內(nèi)的那個(gè)官方文檔钞速,太老了。然后地圖的一些顯示和效果也都有例子嫡秕。建議把官方demo跑一下渴语,就能知道可以做些什么。