百度地图离线地图实现

文章目录

前言
一、离线地图准备

1、使用离线地图时一般需要先下载瓦片图,这里使用全能电子地图下载器
2、将下载的瓦片图放到服务器上,或者本地启个nginx测试使用
3、全能电子地图下载器下载链接(百度网盘)

二、百度地图离线地图实现

1、一些简单的功能都可以离线实现,比如点、点聚合之类
2、实现上面功能前还需要一些基础的配置才行
3、最重要的就是demo了,马上呈现(百度网盘)

总结


前言

内网环境使用地图时只能使用离线地图,还有就是解决百度地图有时候一直提示“未获取百度地图商用版权”问题,所以来尝试使用离线地图

一、离线地图准备

1、使用离线地图时一般需要先下载瓦片图,这里使用全能电子地图下载器

注意:因为使用的是百度地图,地图选择时请选择百度地图,一般地图级别到15级就够用了,当然地图级别越高地图也可以放大更多,瓦片图占用存储空间也越大。另外瓦片图下载完成后不要拼接地图,要选择否;

2、将下载的瓦片图放到服务器上,或者本地启个nginx测试使用

确保瓦片图可以正常访问即可

3、全能电子地图下载器下载链接(百度网盘)

链接: https://pan.baidu.com/s/19M-u2k6YsbTHvjQJVYSo4Q 提取码: 1FFS

二、百度地图离线地图实现

1、一些简单的功能都可以离线实现,比如点、点聚合之类

实现代码如下:

<template>
    <div id="container"></div>
</template>

<script>
export default {
            
    name: 'HelloWorld',
    data() {
            
        return {
            
            // 地图实例
            map: null,
            // 点实例
            mk: null
        }
    },
    created() {
            
        // 加载地图
        this.$nextTick(() => {
            
            this.initMap()
        })
    },
    methods: {
            
        // 获取地图
        initMap() {
            
            // 内网使用-地图对象-在public/index.html引入文件
            let BMap = window.BMap;
            // 创建Map实例
            this.map = new BMap.Map('container');
            
            // 使用卫星地图
            // this.map.setMapType(BMAP_HYBRID_MAP);

            // 地图中心点-经纬度决定我们加载哪里的地图
            var Point = new BMap.Point(113.664653, 34.75291);
            // 初始化地图中心点和放大级别
            this.map.centerAndZoom(Point, 11)
            // 限制地图放大等级-为什么限制
            // 1.因为内网时我们访问不到公网百度地图数据资源
            // 2.同时这里地图放大等级也对应着我们下载的瓦片图资源
            this.map.setMaxZoom(15)
            //开启鼠标滚轮缩放
            this.map.enableScrollWheelZoom(true)

            // 添加中心标注点
            // this.mk = new BMap.Marker(Point)
            // this.map.addOverlay(this.mk);
            this.setMarkerClusterer();
            this.getBoundaryss('郑州', this.map)
        },
        // 点聚合
        setMarkerClusterer() {
            
            let BMap = window.BMap;
            const BMapLib = window.BMapLib;
            // 创建Marker标注
            var pt1 = new BMap.Point(113.673707,34.761689);
            var marker1 = new BMap.Marker(pt1);
            var pt2 = new BMap.Point(113.673707,34.760977);
            var marker2 = new BMap.Marker(pt2);
            new BMapLib.MarkerClusterer(this.map, {
            
                markers: [marker1, marker2],
                gridSize: 60,
                // 最小的聚合数量,小于该数量的不能成为一个聚合,默认为2
                // minClusterSize: 2,
                // 聚合的最大地图级别
                maxZoom: 14,
                styles: [{
            
                    url: require('@/assets/images/text-image.png'), // 点聚合图标背景图
                    size: new BMap.Size(45, 45), // 点聚合图标大小
                    textColor: '#fff'
                    // opt_textSize: 10
                }]
            })
        },

        // 市级高亮==>这里使用的是天地图获取的边界数据,也可以保存下来使用本地JSON数据
        getBoundaryss(name, map) {
            
            const tMapKey = 'ccecd4fb18a2d7c01606c82191dfe619';
            const url = `https://api.tianditu.gov.cn/v2/administrative?keyword=${name}&childLevel=0&extensions=true&tk=${tMapKey}`;
            fetch(url)
                .then(response => response.json())
                .then(data => {
            
                    if (data.status == 200) {
             // status为0表示查询成功
                        // console.log(data);
                        let boundary = data.data.district[0].boundary.replace('MULTIPOLYGON(((', '').replace(')))', '').split(',');
                        boundary = boundary.map(item => item.split(' ').join(','));
                        boundary = boundary.join(';');
                        const BMap = window.BMap;

                        // 需要绘制边界多边形的点集合
                        const paths = [];
                        // 3获取点数组,push到 paths中
                        let firstPoint;
                        // var pointliststr = lengths;
                        var pointliststr = boundary;
                        // console.log('pointliststr', pointliststr);

                        var pointlist = pointliststr.split(';');
                        // console.log(pointlist);
                        // console.log(pointlist[0]);
                        for (var i = 0; i < pointlist.length; i++) {
            
                            var tempPt = pointlist[i].split(',');
                            var newPoint = new BMap.Point(tempPt[0], tempPt[1]);
                            if (i == 0) {
            
                                firstPoint = newPoint;
                            }

                            paths.push(newPoint);
                        }
                        // 第一点再推进去,形成一个闭环,构造了多边形的内环
                        paths.push(firstPoint);

                        // 自定义的八个便捷点,从东开始逆时针,东,东北,北,西北,西,西南,南,东南(必须按顺序来)
                        paths.push(new BMap.Point(170.672126, 39.623555));
                        paths.push(new BMap.Point(170.672126, 81.291804));
                        paths.push(new BMap.Point(105.913641, 81.291804));
                        paths.push(new BMap.Point(-169.604276, 81.291804));
                        paths.push(new BMap.Point(-169.604276, 39.623555));
                        paths.push(new BMap.Point(-169.604276, -68.045308));
                        paths.push(new BMap.Point(105.913641, -68.045308));
                        paths.push(new BMap.Point(170.672126, -68.045308));
                        paths.push(new BMap.Point(170.672126, 39.623555));

                        // 4绘制第一个多边形,覆盖住除行政区外的所有部分,fillColor:填充色,strokeColor:边界颜色(设置透明,否则会有其他线条),strokeOpacity:线条透明,fillOpacity:填充物透明。
                        var ply1 = new BMap.Polygon('', {
            
                            fillColor: '#000',
                            strokeColor: 'transparent',
                            strokeOpacity: 0,
                            fillOpacity: 0.2
                        }); // 建立多边形覆盖物
                        // 将之前形成的点set到多边形对象中
                        ply1.setPath(paths);
                        // 在地图上添加第一个多边形
                        map.addOverlay(ply1); // 遮罩物是半透明的,如果需要纯色可以多添加几层

                        // 5. 给目标行政区划添加边框,其实就是给目标行政区划添加一个没有填充物的遮罩层,绘制出边界线
                        var ply = new BMap.Polygon(boundary, {
            
                            strokeWeight: 1,
                            strokeColor: '#0082ff',
                            fillColor: 'transparent'
                        });
                        map.addOverlay(ply);
                        map.setViewport(ply.getPath()); // 调整视野
                    } else {
            
                        // console.log('未找到该区域');
                    }
                })
                .catch(error => {
            
                    console.error('错误:', error);
                });
        },
    }
}
</script>
<style>
.anchorBL {
            
    display: none;
}
</style>
<style scoped>
#container {
              
    width: 100vw;
    height: 100vh;
}
</style>


2、实现上面功能前还需要一些基础的配置才行

(1)将map整个文件夹复制到项目中的public文件夹下
(2)更改map3.0)int.js中的瓦片图地址,主要是bmapConfig属性中的tiles_path、如果需要使用卫星地图也要配置tiles_satellite_path

/**
 * 离线API初始化, 请在加载map3.0.js之前引入
 */

/**
 * 这是必须要确认的配置
 * 瓦片图必须是png图像
 */
var bmapConfig = {
            
  'tiles_path': 'https://xx.xx.com/hb-baidu-map',      //显示普通地图,为空默认在 tiles/ 目录
  'tiles_satellite_path': 'https://xx.xx.com/hb-baidu-map', //显示卫星影像,为空默认在 tiles_satellite/ ,只有底图没有地址标注
  'tiles_hybrid_path': 'https://xx.xx.com/hb-baidu-map'  //显示带有街道的卫星影像,为空默认在 tiles_hybrid/,需和卫星影像配合使用
}
//获得API主目录,一般不需要修改
var scripts = document.getElementsByTagName("script")
var _JS__FILE__ = scripts[scripts.length - 1].getAttribute("src")
bmapConfig.home_dir = _JS__FILE__.substr(0, _JS__FILE__.lastIndexOf("/"))
if (bmapConfig.tiles_path.length == 0) {
            
  bmapConfig.tiles_path = bmapConfig.home_dir + "/tiles"
}
if (bmapConfig.tiles_satellite_path.length == 0) {
            
  bmapConfig.tiles_satellite_path = bmapConfig.home_dir + "/tiles_satellite"
}
if (bmapConfig.tiles_hybrid_path.length == 0) {
            
  bmapConfig.tiles_hybrid_path = bmapConfig.home_dir + "/tiles_hybird"
}
//调试日志,请保留
function bmapLog (s) {
            
  if (typeof console != 'undefined')
    console.log('>>> ' + s)
}


// 下面可以保持不动
var scripts = document.getElementsByTagName('script')
var JS__FILE__ = scripts[scripts.length - 1].getAttribute('src') //获得当前js文件路径
bmapConfig.home = JS__FILE__.substr(0, JS__FILE__.lastIndexOf('/') + 1) //地图API主目录


;(function () {
            
  window.BMap_loadScriptTime = new Date().getTime()
  //加载地图API主文件 
  document.write(
    '<script type="text/javascript" src="' +
      bmapConfig.home +
      'map3.0.js"></script>'
  )
})()

(3)在public的index.html文件中引入地图文件

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title><%= htmlWebpackPlugin.options.title %></title>
    <!-- 离线地图使用时需要引入的三个文件 -->
    <script
        type="text/javascript"
        src="<%= BASE_URL %>map/map3.0_init.js"
    ></script>
    <script
        type="text/javascript"
        src="<%= BASE_URL %>map/TextIconOverlay_min.js"
    ></script>
    <script
        type="text/javascript"
        src="<%= BASE_URL %>map/MarkerClusterer_min.js"
    ></script>
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work
        properly without JavaScript enabled. Please enable it to
        continue.</strong
      >
    </noscript>
    <div></div>
    <!-- built files will be auto injected -->
  </body>
</html>

3、最重要的就是demo了,马上呈现(百度网盘)

百度离线地图Demo
链接: https://pan.baidu.com/s/1usccGgJ6eh3AZUFctOpjog 提取码: 1FFS

总结

浅浅尝试一下,有更好的思路的话,可以共同讨论一下!

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容