android实现高德地图自定义样式

262 阅读2分钟

需求:去除高德地图上复杂的道路路线、城市标准等 效果如下图:

image.png

1.尝试用高德定义好的的方法 并不能实现

getCurMap()?.apply {
    setOnMapLoadedListener {
        this.mapType = AMap.MAP_TYPE_NORMAL
        //设置是否显示地图上的文字标注(如地名、路名等
        this.showMapText(false)
        //设置是否显示正在建设中的道路
        this.setConstructingRoadEnable(false)
        //设置是否启用实时交通信息
        this.isTrafficEnabled = false
        this.showBuildings(false)
        setCustomMap()
    }
}

2.尝试用高德自定义样式

自定义地图 image.png

有标准模版 、基础模板 、 高级模板 除了标准模版 其他都要收费 不过标准模版 已经可以满足大部分开发需求了 根据需求选择可以实现自己功能的地图模式

3.创建标准模版 然后根据自己需求 可以隐藏或显示 某个底图 也可以设置颜色

image.png

4. 下图中1号按钮为保存2号按钮为导出地图样式

image.png

5. 发布设置好的高德自定义样式 然后下载android离线压缩文件

image.png

image.png

下面开始正式使用此文件(关于地图的显示本文不做赘述,可自行查看官方文档),解压之后获取到两个文件(官网说是三个文件,但是我这里是两个文件,可能是因为我使用的是免费版的原因)

image.png

6.将文件放到项目中

复制两个文件放到res > assets(如果没有可以自行创建) 文件夹下

image.png

7.把下载好的样式 设置到集成的高德地图控件上

private fun setCustomMap() {
    val mapStyleOptions = CustomMapStyleOptions()
    setMapCustomStyleFile(context,mapStyleOptions)
    setMapCustomStyleExtraFile(context,mapStyleOptions)
    // 设置自定义样式
    mapStyleOptions.setEnable(true)
    //mapStyleOptions.setStyleId("your id");
    getCurMap()?.setCustomMapStyle(mapStyleOptions)
}
private fun setMapCustomStyleExtraFile(context: Context,mapStyleOptions:CustomMapStyleOptions) {
    val styleName = "style_extra.data"
    var inputStream: InputStream? = null
    try {
        inputStream = context.assets.open(styleName)
        val b = ByteArray(inputStream.available())
        inputStream.read(b)

        if (mapStyleOptions != null) {
            // 设置自定义样式
            mapStyleOptions.setStyleExtraData(b)
        }
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        try {
            inputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

private fun setMapCustomStyleFile(context: Context,mapStyleOptions:CustomMapStyleOptions) {
    val styleName = "style.data"
    var inputStream: InputStream? = null
    try {
        inputStream = context.assets.open(styleName)
        val b = ByteArray(inputStream.available())
        inputStream.read(b)

        if (mapStyleOptions != null) {
            // 设置自定义样式
            mapStyleOptions.setStyleData(b)
        }
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        try {
            inputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}