文章目录

  • 接入步骤
  • 本地化
  • 放大地图
  • 画标记,画线
  • 闪退原因
  • 图层问题
  • 反地理编码
  • 两点之间的距离
  • 相机始终在运动点的范围内
  • 表达式用于数据驱动样式

接入步骤

之前并没有接过地图的经验,所以看文档也用了一段时间,
1.在mapbox官网注册账号,获取access_token,secret_token,如果地图样式要用mapbox studio做的,token就不能用默认的
2.在module 的build.gradle 导入库 api ‘com.mapbox.mapboxsdk:mapbox-android-sdk:9.6.1’,我使用9.6.1版本,v10现在也已出,不过看文档较少,就先用这个版本试试水
3.在project的build.gradle 导入

allprojects {repositories {google()jcenter()mavenCentral()maven {url 'https://api.mapbox.com/downloads/v2/releases/maven'authentication {basic(BasicAuthentication)}credentials {// Do not change the username below.// This should always be `mapbox` (not your username).username = 'mapbox'// Use the secret token you stored in gradle.properties as the passwordpassword = 'YOUR_TOKEN'}}}
}

4.在gradle.properties 中加入secret_token

MAPBOX_DOWNLOADS_TOKEN=YOUR_TOKEN

5.在清单文件中加入权限

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

6.在application中统一初始化地图

Mapbox.getInstance(mContext!!, mContext!!.getString(R.string.mapbox_access_token))

7.正式接入地图
通过AndroidView 在flutter中调用android的地图代码,加载地图之前要确保定位权限已开,否则闪退

 private val mapView: MapView = MapView(context)private lateinit var mapboxMap: MapboxMapinit {this.mapView.onCreate(null)this.mapView.getMapAsync{ mapboxMap ->this.mapboxMap = mapboxMapmapboxMap.setStyle(Style.DARK) {// Create and customize the LocationComponent's optionsval customLocationComponentOptions = LocationComponentOptions.builder(context).trackingGesturesManagement(true).pulseEnabled(true)//设置打开定位脉冲.pulseColor(0x770000FF)  //设置脉冲颜色.pulseInterpolator(BounceInterpolator())  //设置脉冲动画插值.bearingDrawable(R.mipmap.ic_run_location)  //设置定位图标图片.accuracyColor(Color.TRANSPARENT)   .build()val locationComponentActivationOptions = LocationComponentActivationOptions.builder(context, it).locationComponentOptions(customLocationComponentOptions).useDefaultLocationEngine(true).build()// Get an instance of the LocationComponent and then adjust its settingsmapboxMap.locationComponent.apply {// Activate the LocationComponent with optionsactivateLocationComponent(locationComponentActivationOptions)// Enable to make the LocationComponent visibleisLocationComponentEnabled = true// Set the LocationComponent's camera modecameraMode = CameraMode.TRACKING_COMPASS// Set the LocationComponent's render moderenderMode = RenderMode.COMPASS}}}}

本地化

mapbox虽是全球地图,但中国的地图没有高德详细,但。。。懂的都懂,没办法只能替换了,如果想要地图的语言适配设备语言,只需要加入另一个库

api 'com.mapbox.mapboxsdk:mapbox-android-plugin-localization-v9:0.12.0'
private val mapView: MapView = MapView(context)private lateinit var mapboxMap: MapboxMap**private lateinit var localizationPlugin:LocalizationPlugin**init {this.mapView.onCreate(null)this.mapView.getMapAsync{ mapboxMap ->this.mapboxMap = mapboxMapmapboxMap.setStyle(Style.Builder().fromUri("asset://style.json")) {**localizationPlugin = LocalizationPlugin(mapView, mapboxMap, it)try {localizationPlugin.matchMapLanguageWithDeviceDefault()} catch (exception:RuntimeException) {Log.d("lii", exception.toString())}**// Create and customize the LocationComponent's optionsval customLocationComponentOptions = LocationComponentOptions.builder(context).trackingGesturesManagement(true).pulseEnabled(true).pulseColor(0x770000FF).pulseInterpolator(BounceInterpolator()).bearingDrawable(R.mipmap.ic_run_location).accuracyColor(Color.TRANSPARENT).build()val locationComponentActivationOptions = LocationComponentActivationOptions.builder(context, it).locationComponentOptions(customLocationComponentOptions).useDefaultLocationEngine(true).build()// Get an instance of the LocationComponent and then adjust its settingsmapboxMap.locationComponent.apply {// Activate the LocationComponent with optionsactivateLocationComponent(locationComponentActivationOptions)// Enable to make the LocationComponent visibleisLocationComponentEnabled = true// Set the LocationComponent's camera modecameraMode = CameraMode.TRACKING_COMPASS// Set the LocationComponent's render moderenderMode = RenderMode.COMPASS}}}}

放大地图

之前用如下代码放大地图,时大时小的
//mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(17.0))
之后改用如下操作,最大最小缩放值都设置
mapboxMap.setMaxZoomPreference(17.0)
mapboxMap.setMinZoomPreference(16.0)

画标记,画线

由于数据源各不相同,所以只列了画线核心代码

lineManager = LineManager(mapView, mapboxMap, it)
var lineOptions =  LineOptions().withLatLngs(it)   //把坐标数组放入接口.withLineColor(ColorUtils.colorToRgbaString(Color.argb(255, 255, 91, 61))).withLineWidth(5.0f)lineManager.lineCap = Property.LINE_CAP_ROUND  //设置圆角,避免画的线不平滑lineManager.create(lineOptions)
    private val START_SOURCE_ID = "start_source_id"private val START_LAYER_ID = "start_layer_id"private val START_IMAGE_ID = "start_image_id"val source = GeoJsonSource(START_SOURCE_ID)source.setGeoJson(Point.fromLngLat(start[1],start[0]))style.addSource(source)style.addImage(START_IMAGE_ID, mContext.getDrawable(R.drawable.ic_map_start)!!)val symbolLayer = SymbolLayer(START_LAYER_ID, START_SOURCE_ID).withProperties(/* show image with id title based on the value of the name feature property */iconImage(START_IMAGE_ID),/* set anchor of icon to bottom */iconAnchor(Property.ICON_ANCHOR_BOTTOM),/* all info window and marker image to appear at the same time*/iconAllowOverlap(true),iconSize(0.5f),iconOffset(arrayOf(-10f, 5f)))style.addLayer(symbolLayer)

闪退原因

刚接入mapbox时经常闪退,每次退出此地图,或者进入另一个地图就会闪退,提示

You're calling `cancelTransitions` after the `MapView` was destroyed, were you invoking it after `onDestroy()`?You're calling `jumpTo` after the `MapView` was destroyed, were you invoking it after `onDestroy()`?You're calling `getCameraValues` after the `MapView` was destroyed, were you invoking it after `onDestroy()`?java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object referenceat android.animation.PropertyValuesHolder.setObjectValues(PropertyValuesHolder.java:663)at android.animation.PropertyValuesHolder.ofObject(PropertyValuesHolder.java:406)at android.animation.ValueAnimator.setObjectValues(ValueAnimator.java:524)at com.mapbox.mapboxsdk.location.MapboxAnimator.<init>(MapboxAnimator.java:67)at com.mapbox.mapboxsdk.location.MapboxLatLngAnimator.<init>(MapboxLatLngAnimator.java:13)at com.mapbox.mapboxsdk.location.MapboxAnimatorProvider.latLngAnimator(MapboxAnimatorProvider.java:28)at com.mapbox.mapboxsdk.location.LocationAnimatorCoordinator.createNewLatLngAnimator(LocationAnimatorCoordinator.java:332)at com.mapbox.mapboxsdk.location.LocationAnimatorCoordinator.updateCameraAnimators(LocationAnimatorCoordinator.java:292)at com.mapbox.mapboxsdk.location.LocationAnimatorCoordinator.feedNewLocation(LocationAnimatorCoordinator.java:118)at com.mapbox.mapboxsdk.location.LocationComponent.updateLocation(LocationComponent.java:1622)at com.mapbox.mapboxsdk.location.LocationComponent.updateLocation(LocationComponent.java:1593)at com.mapbox.mapboxsdk.location.LocationComponent.access$1000(LocationComponent.java:103)at com.mapbox.mapboxsdk.location.LocationComponent$CurrentLocationEngineCallback.onSuccess(LocationComponent.java:1809)at com.mapbox.mapboxsdk.location.LocationComponent$CurrentLocationEngineCallback.onSuccess(LocationComponent.java:1797)at com.mapbox.android.core.location.MapboxFusedLocationEngineImpl$MapboxLocationEngineCallbackTransport.onLocationChanged(MapboxFusedLocationEngineImpl.java:117)at android.location.LocationManager$LocationListenerTransport.acceptLocation(LocationManager.java:2742)at android.location.LocationManager$LocationListenerTransport.lambda$enkW18B0WwpQkSIMmVChmQ2YwC8(Unknown Source:0)at android.location.-$$Lambda$LocationManager$LocationListenerTransport$enkW18B0WwpQkSIMmVChmQ2YwC8.accept(Unknown Source:6)at com.android.internal.util.function.pooled.PooledLambdaImpl.doInvoke(PooledLambdaImpl.java:292)at com.android.internal.util.function.pooled.PooledLambdaImpl.invoke(PooledLambdaImpl.java:201)at com.android.internal.util.function.pooled.OmniFunction.run(OmniFunction.java:97)at android.os.Handler.handleCallback(Handler.java:938)at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:236)at android.app.ActivityThread.main(ActivityThread.java:8043)at java.lang.reflect.Method.invoke(Native Method)at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)

看到LocationComponent字眼,想到是不是加入定位功能才出现的bug,屏蔽后果然不会闪退了,于是在销毁地图时把定位功能关闭,或许定位时有动画没有销毁导致空指针异常

override fun dispose() {mapboxMap.locationComponent.onStop()mapView.onDestroy()}

图层问题

在画线和画标记时,图层的叠加渲染问题,点的图层在线上还是在线下是个问题,
之前没用symbleLayer 而是用symbleManager

    private lateinit var symbolManager:SymbolManagerprivate lateinit var symbol: SymbolsymbolManager = SymbolManager(mapView, mapboxMap, it)style.addImage("ic_map_start",com.mapbox.mapboxsdk.utils.BitmapUtils.getBitmapFromDrawable(mContext.getDrawable(R.drawable.ic_map_start))!!,false)
symbolManager.iconAllowOverlap = trueval start = drawMapLine.list[0]// Add symbol at specified lat/lonsymbol = symbolManager.create(SymbolOptions().withLatLng( LatLng(start[0], start[1])).withIconImage("ic_map_start").withIconSize(0.5f).withDraggable(true))

用addLayer()就会符合正常逻辑一样,后add的Layer则在上层

反地理编码

mapbox有提供API对坐标进行反地理编码,location为经度,纬度组合字符串,types筛选了省市级别,语言筛选为简体中文,默认返回英文省市,根据返回的json格式,获取想要的信息即可

https://api.mapbox.com/geocoding/v5/mapbox.places/{location}.json?access_token=“”&types=place,region&language=zh-CN

两点之间的距离

location即为两点坐标,以分号间隔,这个接口是路线规划API,只是其中包含了距离字段,其中有骑行,跑步,走路的路线规划。

https://api.mapbox.com/directions/v5/mapbox/cycling/{location}?access_token=“”

相机始终在运动点的范围内

其实就是把相机移动到该点的位置

mapboxMap.animateCamera(CameraUpdateFactory.newLatLng(sections.last().last()))

表达式用于数据驱动样式

表达式(Expression)是我遇到的难点,之前一直没怎么看懂,想要在一条线上画不同的颜色,分小段画太费时,需要10s左右,这还是可以解决的点,但是线段一旦太多,必须要放大到一定程度才能看到完整线段,换成点画成线,放大之后就是离散的点了。。。。这个可不好控制,毕竟坐标点数随机,也不可能去找这种规律,直接放弃。找遍所有的例子,发现路线渐变颜色还是有点沾边,只是不知道stop()要怎么控制,还看了一个根据树木大小画不同半径大小的圆在地图上的例子,虽然例子与实际场景很接近,但是源不一样,就不知道如何下手,打开链接看看里面的源是怎么回事,发现他已经做成了一个瓦片集,每棵树位置都已经在地图上,可是实际场景的源是一串坐标点,也许也可以根据每个点设置颜色属性,再根据该属性设置线的颜色,不过没试过,本人用的渐变颜色

style.addLayer(LineLayer("linelayer", "line-source").withProperties(lineCap(Property.LINE_CAP_ROUND),lineJoin(Property.LINE_JOIN_ROUND),lineWidth(5.0f),lineGradient(interpolate(linear(), lineProgress(), *arrayStop))  //关键代码,利用线性插值,由0到1,逐渐改变每点的颜色,就把线段分成10个点,每个点的颜色放到arrayStop数组里 ,如[stop(1/10, Colors.RED),stop(2/10, Colors.YELLOW)],   linear(), lineProgress()都是表达式,还有zoom(),甚至根据自己定义的属性取值如get("DBH"),相对interpolate 还有step ,match ))

Flutter 接入MapBox地图相关推荐

  1. flutter集成高德地图获取位置

    flutter集成高德地图获取位置 准备工作 在创建安卓应用 获取SHA1 获取当前位置 添加依赖 文件配置 build.gradle文件配置 AndroidManifest.xml配置 获取定位 准 ...

  2. vue中,应用mapbox地图(一)——mapbox-gl地图设置中文是zh-Hans不是zh accessToken-访问令牌 正确版本streets-v11

    vue中,应用mapbox地图(一)--mapbox-gl地图设置中文是zh-Hans不是zh & accessToken-访问令牌 & 正确版本streets-v11 Mapbox ...

  3. 微信小程序 接入第三方地图

    文章目录 一.接入腾讯地图 1.引入微信jdk 2.声明腾讯地图实例 3.获取当前定位 4.微信小程序相关配置 二.接入高德地图 1.导入相关sdk 2.声明地图实例化 3.获取当前定位API 总结 ...

  4. mapbox中文地图_使用 Mapbox 地图

    如果您可以访问 Mapbox 地图,则可以将其添加至您的工作簿,或者使用它们在 Tableau Desktop 中创建地图视图.有关特定于国家/地区的可用数据的列表,请参见支持的地图数据. 将使用 M ...

  5. vue中,应用mapbox地图——地图组件mapbox-gl和语言包@mapbox/mapbox-gl-language地图英文转中文 accesstokens-访问令牌移动端地图-leaflet

    vue中,应用mapbox地图--地图组件mapbox-gl和语言包@mapbox/mapbox-gl-language用于将地图上的英文转中文 & accesstokens-访问令牌 &am ...

  6. 在iOS中进行Mapbox地图开发杂谈

    最近因项目需要,在app中要集成Mapbox,并且要能与苹果地图切换使用.从最早认识Mapbox到最终集成完毕,中间有一些断断续续,但总的时间也不算短了,关于这方面的资料其实是比较少的,能参考的基本都 ...

  7. 快速接入百度地图定位、描点

    这里整理一下接入 百度地图 的流程,做一下记录(基于 Kotlin 语言开发). 第一步,肯定还是注册账号,创建应用了. 先来到百度地图 首页 登录自己或公司的 百度账号(公司项目,一般都是由公司提供 ...

  8. Python地理可视化:plotly绘制mapbox地图热力密度图

    Python地理可视化:plotly绘制mapbox地图热力密度图 import plotly.graph_objects as go import numpy as npKEYS = ['中心点经纬 ...

  9. 使用cesium加载mapbox地图底色的办法

    使用cesium加载mapbox地图底色的办法 安装:vue-cli-plugin-cesium插件 vue-cli-plugin-cesium - npm 获取cesium的token: 申请ces ...

最新文章

  1. [THUWC2017]随机二分图
  2. c语言编程常见问题解答 pdf,[编程语言]C语言常见问题集pdf pdf文件[1.35MB]-码姐姐下载...
  3. 数组的partition调整
  4. java 链表反转_LeetCode206 实现单链表的反转
  5. 01-Flutter移动电商实战-项目学习记录
  6. Fresco 二三事:图片处理之旋转、缩放、裁剪切割图片
  7. Spring MVC 流程图
  8. ural 1353. Milliard Vasya's Function
  9. 【LeetCode】剑指 Offer 52. 两个链表的第一个公共节点
  10. 更新fielddata为true_关于ElasticSearch的聚类时出现fielddata=true问题
  11. Linux之telnet命令
  12. Network 第九篇 - 双机热备-HSRP
  13. 轻快pdf阅读器 电子书阅读软件电脑版
  14. TSP问题详解(旅行商问题)
  15. 在FireFox中使用IE Tab插件
  16. linux 上传下载测速
  17. 微信字体大小调整导致的H5页面错乱问题处理
  18. Axure视频教程2:制作第一个原型
  19. 如何利用社交媒体进行跨境电商营销—扬帆际海
  20. python 操作键盘,鼠标 。我这个是自动企业微信加好友的,源码可以修改成别的。挺好使!

热门文章

  1. MyBatis 缓存机制
  2. linux总结(思维导图)
  3. Vuex的使用(十)——mutations和actions的返回值测试
  4. LockChain—打造区块链行业的东方财富网
  5. Java随堂小记09(GUI)
  6. mysql: however file don't exists. Create writable for user 'mysql'.
  7. 文本文件和二进制文件学习
  8. 嵌入式Android底层开发(三)硬件访问服务框架
  9. 15分钟安装MySQL[如何彻底卸载旧mysql+重装+测试]
  10. 电路-并联谐振电路分析