地图下钻,双击返回上一级

介绍:
看了好多地图下钻的案例,要么json文件不全胡,要么返回功能不全胡,有的返回是直接写死,返回到首页,我这个小案例是使用地理小工具的数据,本案例可以逐步一级一级的返回,地图的其他样式可以根据项目需求在option中配置。

lodash4.17.21版本:

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    #chart-panel {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }
  </style>

  <script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.2.1/echarts.min.js"></script>
  <!-- <script src="https://lib.baomitu.com/echarts/4.1.0/echarts.min.js"></script> -->
  <script src=""></script>
  <script src="./静态资源/Lodash4.17.21.min.js"></script>
  <script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
  <!-- <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.1/echarts.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.2.1/echarts.min.js"></script> -->
</head>

<body>
  <div id="chart-panel" style="margin-top:30px"></div>
  <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
  <script type="text/javascript">
    //各省份的数据
    var allData = [
      {
        name: '北京'
      }, {
        name: '天津'
      }, {
        name: '上海'
      }, {
        name: '重庆'
      }, {
        name: '河北'
      }, {
        name: '河南'
      }, {
        name: '云南'
      }, {
        name: '辽宁'
      }, {
        name: '黑龙江'
      }, {
        name: '湖南'
      }, {
        name: '安徽'
      }, {
        name: '山东'
      }, {
        name: '新疆'
      }, {
        name: '江苏'
      }, {
        name: '浙江'
      }, {
        name: '江西'
      }, {
        name: '湖北'
      }, {
        name: '广西'
      }, {
        name: '甘肃'
      }, {
        name: '山西'
      }, {
        name: '内蒙古'
      }, {
        name: '陕西'
      }, {
        name: '吉林'
      }, {
        name: '福建'
      }, {
        name: '贵州'
      }, {
        name: '广东'
      }, {
        name: '青海'
      }, {
        name: '西藏'
      }, {
        name: '四川'
      }, {
        name: '宁夏'
      }, {
        name: '海南'
      }, {
        name: '台湾'
      }, {
        name: '香港'
      }, {
        name: '澳门'
      }];

    // 基于准备好的dom,初始化echarts实例
    var myChart = echarts.init(document.getElementById('chart-panel'));
    for (var i = 0; i < allData.length; i++) {
      allData[i].value = Math.round(Math.random() * 100);
    }

    var allmapdata = [];//每点击一次,都将获取的地图level、name和mapcode储存在数组中
    var bigArray = [];//保存所有点击过的区域显示的地图,不重复的数组
    var timeFn = null;
    var click_history_path_Arry = [];//点击的历史记录

    click_history_path_Arry.push({//初始历史记录
      type: 'FeatureCollection',
      level: 'country',
      name: '中国',
      adcode: 'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=100000_full'
    })
    localStorage.setItem('click_history_path_Arry', JSON.stringify(click_history_path_Arry))
    console.log('初始历史记录:', click_history_path_Arry);
    loadMap('https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=100000_full', '中国');  //初始化地图


    /**
     获取对应的json地图数据,然后向echarts注册该区域的地图,最后加载地图信息
     @params {String} mapCode:json数据的地址
     @params {String} name: 地图名称
     */
    function loadMap(mapCode, name) {
      $.get(mapCode, function (data) {
        console.log('传入省份json网址的数据:', data.features);

        var detail_data = []
        // 从中国地图数据中获取每个省份的名字
        // console.log("获取点击后的下一级数据:");
        // console.log("子节点数量:", data.features.length);
        data.features.forEach(item => {
          // console.log( item.type, item.properties.level, item.properties.name, item.properties.adcode);
          if (item.properties.level == 'province') {
            detail_data.push({
              type: item.type,
              level: item.properties.level,
              name: item.properties.name,
              adcode: 'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=' + item.properties.adcode + '_full'
            })

          }
          else if (item.properties.level == 'city') {
            detail_data.push({
              type: item.type,
              level: item.properties.level,
              name: item.properties.name,
              adcode: 'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=' + item.properties.adcode + '_full'
            })

          }
          else if (item.properties.level == 'district') {
            detail_data.push({
              type: item.type,
              level: item.properties.level,
              name: item.properties.name,
              adcode: 'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=' + item.properties.adcode
            })

          }
        });
        allmapdata.push(...detail_data)//将点击后显示的区域都追加到allmapdata数组
        bigArray = _.uniqWith(allmapdata, _.isEqual);//利用loadsh进行数组去重

        // 将 bigArray 转换为字符串,并保存到 localStorage  
        localStorage.setItem('bigArray', JSON.stringify(bigArray));
        //console.log('全量不重复数据:', bigArray);//这个数组数据很有用

        if (data) {
          echarts.registerMap(name, data);

          var option = {
            tooltip: {
              show: true,
              textStyle: {
                color: '#681752',//文字的颜色。
                fontStyle: 'normal',//文字字体的风格。
                fontWeight: 'bolder',
                fontSize: 20,
                textBorderWidth: 4,
                textBorderType: 'solid',
              },
              formatter: function (params) {
                if (params.data) return params.name + ':' + params.data['value']
              },
            },
            // 视觉映射组件,用于视觉编码,如颜色、大小等  
            visualMap: {
              type: 'continuous',//连续型数据 
              text: ['', ''],// 文本,默认为数值文本,为空时则不显示  
              showLabel: false,//false    true// 是否显示文字标签 
              left: '50',// 组件离容器左侧的距离 
              min: 0,// 映射的最小值 
              max: 100,// 映射的最大值  
              inRange: {// 在视觉映射范围内的视觉元素  
                color: ['#edfbfb', '#b7d6f3', '#40a9ed', '#3598c1', '#215096',]
              },
              splitNumber: 0,// 这里设置为0可能会按照数据自动计算分割段数 
            },
            //roam: true, // 是否开启鼠标缩放和平移漫游 
            series: [{
              name: 'MAP',
              type: 'map',
              mapType: name, // 使用的地图类型,这里使用了变量 name 来动态指定
              selectedMode: 'false',//是否允许选中多个区域
              layoutCenter: ["50%", "50%"], //地图位置
              layoutSize: "100%",
              zoom: 1, //当前视角的缩放比例
              label: {
                normal: {
                  show: true,// 正常状态下是否显示标签 
                },
                emphasis: {
                  show: true,// 高亮状态下是否显示标签
                }
              },
              data: allData,// 数据内容,这里使用了变量 allData 来动态指定 
            }]
          };

          myChart.setOption(option);
        }
        else {
          alert('json数据不存在,无法加载该地图');
        }
      });
    }

    // 查询函数,通过name属性,查找adcode
    function findAdcodeByName(name, data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].name === name) {
          return data[i].adcode;
        }
      }
      return null; // 如果没有找到,返回null或你想要的任何默认值  
    }

    //单击切换到省级地图,当mapCode有值,说明可以切换到下级地图
    myChart.on('click', function (params) {
      clearTimeout(timeFn);
      //由于单击事件和双击事件冲突,故单击的响应事件延迟250毫秒执行
      // console.log(params);
      timeFn = setTimeout(function () {
        var name = params.name; //获取单击时区域的名字
        const mapCode = findAdcodeByName(name, JSON.parse(localStorage.getItem('bigArray')));//通过name在全量数据中查找mapcode路径

        localStorage.setItem('danji_name', name)//将单击时的区域名字存储本地
        localStorage.setItem('danji_mapcode', mapCode)//将单击时的区域json数据存储本地
        var get_name = localStorage.getItem('danji_name')
        var get_mapcode = localStorage.getItem('danji_mapcode')
        console.log("单击区域名字:", get_name, "单击区域mapcode:", get_mapcode);

        // 当点击的时候将点击区域的名字和mapcode推进历史记录数组
        setTimeout(function () {
          click_history_path_Arry = JSON.parse(localStorage.getItem('click_history_path_Arry'));
          console.log('获取第一次路径:', click_history_path_Arry);

          click_history_path_Arry.push({
            name: get_name,
            adcode: get_mapcode
          })
          click_history_path_Arry = _.uniqWith(click_history_path_Arry, _.isEqual);//利用loadsh进行数组去
          localStorage.setItem('click_history_path_Arry', JSON.stringify(click_history_path_Arry));
          console.log('历史路径:', click_history_path_Arry);//这个有路径
        }, 200)
        if (!mapCode) {
          alert('无此区域地图显示!!!');
          return;
        }
        loadMap(mapCode, name);
      }, 250);
    });
    // 绑定双击事件,返回全国地图
    myChart.on('dblclick', function (params) {
      //当双击事件发生时,清除单击事件,仅响应双击事件
      clearTimeout(timeFn);
      // 对历史路径中的元素进行去重
      var get_click_history_path_Arry = _.uniqWith(JSON.parse(localStorage.getItem('click_history_path_Arry')), _.isEqual)
      console.log('从本地获取的历史路径:', get_click_history_path_Arry);
      // 检查数组是否非空  
      if (get_click_history_path_Arry.length > 1) {
        // 获取倒数第二个元素的索引(因为JavaScript的索引是从0开始的)  
        const lastIndex = get_click_history_path_Arry.length - 2;
        // 访问该索引的name和adcode  
        const his_name = get_click_history_path_Arry[lastIndex].name;
        const his_adcode = get_click_history_path_Arry[lastIndex].adcode;
        // 打印结果  
        console.log('上传名字:', his_name);
        console.log('上传Adcode:', his_adcode);
        loadMap(his_adcode, his_name);
        const newAreas = get_click_history_path_Arry.slice(0, get_click_history_path_Arry.length - 1);
        localStorage.setItem('click_history_path_Arry', JSON.stringify(newAreas))//将删除后的数组覆盖掉本地原有的数组
      }
      else {
        alert('暂无历史记录.');
      }
    });
  </script>
</body>
</html>

效果图片:
在这里插入图片描述
单击进入下一级:
在这里插入图片描述
单击再次进入下一级:
在这里插入图片描述
双击返回上一级:
在这里插入图片描述
返回到首页:
在这里插入图片描述

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值