mapbox分级图

 有很多没用的代码,看关键的generateMarker()

initMap() {
      let style = this.lodash.cloneDeep(window.darkStyle)
      let layer = this.setLayer(style)
      this.map = new window.compassengine.Map({
        container: 'mapContainer',
        style: style,
        maxZoom: 18,
        minZoom: 1,
        scrollZoom: true,
        preserveDrawingBuffer: true,
        epsg: 'EPSG:4490'
      })
      this.map.on('load', () => {
        for (const iterator of layer) {
          this.map.addLayer(iterator) //地图注记
        }
        this.map.addControl(new compassengine.ScaleControl(), 'bottom-left')
        this.initgeom(this.tableSelectObj.gde_code)
        this.$nextTick(()=>{
          if (this.onlyXianData.length > 0) {
            this.generateMarker(this.map)
          }
        })
        this.map.on('mousemove', (e) => {
          this.position.lng = e.lngLat.lng
          this.position.lat = e.lngLat.lat
          // 设置鼠标样式
          if (this.map.getLayer('QHFillLayer') && this.map.queryRenderedFeatures(e.point, { layers: ['QHFillLayer'] }).length > 0) {
            this.map.getCanvas().style.cursor = 'pointer'
          } else this.map.getCanvas().style.cursor = null
        })
      })
    },
initgeom(code) {
      if (!code) code = this.code
      let QHlayer = 'geo_xian' // 只需要县级的边界
      let lev =
        code.toString().length == 2
          ? '1'
          : code.toString().length == 4
          ? '2'
          : code.toString().length == 6
          ? '3'
          : '4'
      if (this.map.getSource('QHVector')) {
        // 如果不是第一次加载则直接修改source
        this.map
          .getSource('QHVector')
          .setTiles([
            `${
              CONFIG.Service
            }/queryListMvt/{z}/{x}/{y}.mvt?code=${code}&layer=${QHlayer}&tilematrixset=c&fields=gid,"NAME"&token=${sessionStorage.getItem(
              'access_token'
            )}&joincond={"selfField":"gid","joinField":"gde_code","joinTableId":"af40b1bd-9308-4409-b2e0-a1239f023293","joinAttribute":"房屋经济损失"}`
          ]) // 内层边界
        this.map
          .getSource('centerQHVector')
          .setTiles([
            `${
              CONFIG.Service
            }/queryListMvt/{z}/{x}/{y}.mvt?code=${code}&layer=${QHlayer}&geomfiled=center_geom&tilematrixset=c&fields=gid,"NAME"&token=${sessionStorage.getItem(
              'access_token'
            )}`
          ]) // 点
          this.map
          .getSource('QHShiVector')
          .setTiles([
            `${
              CONFIG.Service
            }/queryListMvt/{z}/{x}/{y}.mvt?code=${code}&layer=geo_shi&tilematrixset=c&fields=gid,"NAME"&token=${sessionStorage.getItem(
              'access_token'
            )}`
          ])//市
      } else {
        // 如果是第一次修改则需要添加source和图层
        this.map.addSource('QHVector', {
          type: 'vector',
          tiles: [
            `${
              CONFIG.Service
            }/queryListMvt/{z}/{x}/{y}.mvt?code=${code}&layer=${QHlayer}&tilematrixset=c&fields=gid,"NAME"&token=${sessionStorage.getItem(
              'access_token'
            )}&joincond={"selfField":"gid","joinField":"gde_code","joinTableId":"af40b1bd-9308-4409-b2e0-a1239f023293","joinAttribute":"房屋经济损失"}`
          ]
        })
        this.map.addSource('centerQHVector', {
          type: 'vector',
          tiles: [
            `${
              CONFIG.Service
            }/queryListMvt/{z}/{x}/{y}.mvt?code=${code}&layer=${QHlayer}&geomfiled=center_geom&tilematrixset=c&fields=gid,"NAME"&token=${sessionStorage.getItem(
              'access_token'
            )}`
          ]
        })
        this.map.addSource('QHShiVector', {
          type: 'vector',
          tiles: [
            `${
              CONFIG.Service
            }/queryListMvt/{z}/{x}/{y}.mvt?code=${code}&layer=geo_shi&tilematrixset=c&fields=gid,"NAME"&token=${sessionStorage.getItem(
              'access_token'
            )}`
          ]
        })
        this.map.addLayer({
          id: 'QHShiLayer',
          type: 'line',
          source: 'QHShiVector',
          'source-layer': 'mvt',
          paint: {
            'line-color': '#00ff00',
            'line-width': 3
          }
        })
        this.map.addLayer({
          id: 'QHLayer',
          type: 'line',
          source: 'QHVector',
          'source-layer': 'mvt',
          paint: {
            'line-color': '#506FAD',
            'line-width': 1
          }
        })
        this.map.addLayer({
          id: 'QHFillLayer',
          type: 'fill',
          source: 'QHVector',
          'source-layer': 'mvt',
          paint: {
            'fill-color': 'rgba(112,165,238,0.47)', 
            // 'fill-outline-color': '#fff',
            // 'fill-opacity':1
          }
        })
        this.map.addLayer({
          id: 'QHPoints',
          type: 'symbol',
          source: 'centerQHVector',
          'source-layer': 'mvt',
          layout: {
            'text-field': ['get', 'NAME'],
            'text-font': ['Open Sans Regular'],
            'text-size': 12,
          },
          paint: {
            'text-color': '#4e76b1',
            'text-halo-color': '#fff',
            'text-halo-width': 2
           }
        })
      }
      this.map.on('click', 'QHFillLayer', (e) => {
        console.log(e.features[0])
      })
      if(this.activeName == 'second'){
        this.createFillColor()
      }
      this.$store.dispatch('getXzqhBoundsByArea', { codes: code, lev: lev }).then((res) => {
        // 地图跳转到图层位置
        const bbox = [
          [res.data.data[0].xmax, res.data.data[0].ymax],
          [res.data.data[0].xmin, res.data.data[0].ymin]
        ]
        this.map.fitBounds(bbox, {
          duration: 1,
          maxZoom: 12,
          padding: { top: 30, bottom: 30, left: 30, right: 30 }
        })
      })
    },

 

    createFillColor() {
      let data = {
        // 填报价格
        conds: [{ operator: 'FQR', field: 'gde_code', value: this.$route.query.code }],
        tablename: 'af40b1bd-9308-4409-b2e0-a1239f023293',
        // groupfields: [{ field: 'gde_code,1,6', type: 'JQ', rename: 'district' }],
        groupfields: [],
        statisconds: [
          { field: '房屋经济损失', type: 'ZDZ', rename: 'max', dpoint: 1 /** 保留位数 */ },
          { field: '房屋经济损失', type: 'ZXZ', rename: 'min', dpoint: 1 }
        ]
      }
      this.$store.dispatch('searchStatisticData', data).then((res) => {
        if (res.data.code == 1) {
          let min = +res.data.data.list[0].min
          let max = +res.data.data.list[0].max
          let step = (max + min) / 5
          let field = '房屋经济损失'
          let expression = ['step', ['to-number', ['get', field]], 'rgba(112,165,238,0.47)']
          // let colorStep = ['#d4c281', '#af9857', '#ad8448', '#7a4707', '#ED561B']
          let colorStep = ['#D0C08C', '#B9A165', '#B18D3F', '#A47C3E', '#9A651F','7B4903']
          for (let i = 0; i < 5; i++) {
            expression.push(min + step * i, colorStep[i])
          }
          // console.log(expression)
          this.map &&
            this.map.getLayer('QHFillLayer') &&
            this.map.setPaintProperty('QHFillLayer', 'fill-color', expression)
          return expression
        }
      })
    },

 

  generateMarker(map) {
      console.log(this.onlyXianData);//所有数据
      this.onlyXianData.forEach((e,index) => {
        if(!e['center_geom']){
          // debugger
          return
        }
        if (!e.children) {
          let id = `marker_${e['行政区划代码']}`
          let el = document.createElement('div')
          el.id = id
          el.className = `gjd-map-chart chartScale ${id}`
          // 添加marker
          el.style.width= '4%'
          el.style.height= '4%'
          el.style.zIndex= '999'
          // debugger
          new window.compassengine.Marker(el).setLngLat(e['center_geom']['coordinates']).addTo(map)
          // 添加图表
          let myChart = this.$echarts.init(document.querySelector(`#${id}`))
          let option = {
            tooltip: {trigger: 'item'},
            legend: {
              data: [`${e['行政区划名称']}(单位:人)`],
              show: false
            },
            xAxis: {
              data:['2018','2019','2020','2021'],
              axisLine: {
                show: false
              },
              axisTick: {
                alignWithLabel: false,
                show: false
              },
              axisLabel: {
                show: false
              }
            },
            yAxis: [{
                type: 'value',
                splitLine: {
                  show: false
                },
                axisLabel: {
                  show: false
                }
            }],
            series: [
              {
                name: `${e['行政区划名称']}(单位:人)`,
                type: 'bar',
                data: [e['2018年同期'], e['2019年同期'], e['2020年同期'],e['2021年同期']],
                colorBy: 'data'
              }
            ],
            color: ['#E85EF2', '#F1892A', '#0A9E4D','#197CD6']
          }
          // TODO 为什么echarts的hover效果没有了?
          // 使用刚指定的配置项和数据显示图表。
          myChart.setOption(option)
          console.log(option);
          // let chartName = `chart_${e['行政区划代码']}`
          // this.chartList[chartName] = myChart
        }
      })
        // console.log(this.chartList);
    }
   onResize() {
      this.$nextTick(()=>{
        this.barChart = this.$echarts.init(this.$refs.bar)
        this.lineChart = this.$echarts.init(this.$refs.line)
        window.addEventListener("resize",function (){
            barChart.resize();
            lineChart.resize(); //去掉this
        })
      })
    }, // 改变浏览器窗口的大小。echarts自适应
    drawChart(data) {
      this.chartsData = []
      for (const key in data) {
      // debugger
        if(key.includes('同期')){ 
          this.chartsData.push({name:key.slice(0,4),num:0,value:data[key] ||0})
        }
        // if(key == 'pid'){break}
      }
      if(data.children){
        this.getXianNum(data.children)
      }else{
        this.onlyXianData.push(data) //如果是县进来没有下级
      }
      // console.log(data,this.chartsData);
      let option = {
        grid: {
          top: '4%',
          left: '3%',
          right: '3%',
          bottom: '5%',
          containLabel: true
        }, // 图表网格
        tooltip: {
          trigger: 'item' // 触发类型可选值有item\axis
        },
        xAxis: {
          type: 'category',
          data: ['2018','2019','2020','2021'],
          axisLine: {
            //  show: false, // 不显示坐标轴线
            lineStyle: {
              color: '#fff'
            }
          },
          splitLine:{
              show:false // 不显示网格线
          },
          axisTick: {
            show: false// 刻度线
          }
        },
        yAxis: {
          type: 'value',
          name: "人数",
          axisLine: {
            // show: false, // 不显示坐标轴线
            lineStyle: {
              color: '#fff'
            }
          },
          splitLine:{
              show:false // 不显示网格线
          },
          // axisTick: {
          //   show: false// 刻度线
          // }
        },
        series: [
          {
            name: '人口',
            type: 'bar',
            color: this.$echarts.graphic.LinearGradient(0, 1, 1, 0, [
              { offset: 0, color: '#2DFDFC' },
              { offset: 1, color: '#506FAD' }
            ]),
            data: this.chartsData
          }
        ]
      }
      // debugger
      this.barChart.setOption(option)
      option.series[0].type = 'line'
      option.series[0].itemStyle = {
              color: '#FD7E51', //改变折线点的颜色
              lineStyle:{ 
                color:'#FD7E51' //改变折线颜色
              }
            }, 
      option.yAxis.name = '次数'
      this.lineChart.setOption(option)
    },
    getXianNum(data){ //递归获取所有县级有数据的个数
      data.forEach(ele => {
        for (const key in ele) {
          if(key.includes('同期') && ele[key] != null){
            for (let i = 0; i <  this.chartsData.length; i++) {
              if( this.chartsData[i].name == key.slice(0,4)){ 
                  this.chartsData[i].num++
                break
              }
            }
          }
        }
        if(ele.children){
          this.getXianNum(ele.children)
        }else if((ele['2018年同期']|| ele['2019年同期']|| ele['2020年同期']||ele['2021年同期'])&& ele.center_geom){
          this.onlyXianData.push(ele)
        }
      });
    },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中使用Mapbox加载片可以通过以下步骤实现: 1. 在main.js文件中导入mapbox-gl库,并将其设置为Vue的原型属性: ```javascript import mapBoxGl from 'mapbox-gl' Vue.prototype.$mapboxgl = mapBoxGl ``` 2. 在Vue组件的template中添加一个包含id为'map'的div元素,用于显示地图: ```html <template> <div id='map' style='width:400px;height:400px'></div> </template> ``` 3. 在Vue组件的script中,使用mounted钩子函数初始化地图: ```javascript <script> export default { mounted() { this.initmap() }, methods: { initmap() { this.$mapboxgl.accessToken = '你的Token' var map = new this.$mapboxgl.Map({ container: "map", style: "mapbox://styles/mapbox/streets-v11", center: [104.07, 30.67], zoom: 5, }); } } } </script> ``` 通过上述步骤,你可以成功加载Mapbox地图并展示在Vue组件中。如果你想在地图中添加片,可以使用Mapbox的API来实现。例如,你可以使用`map.loadImage`方法加载片,并在回调函数中将片添加到地图中。 希望这个回答对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【Vue+Mapbox】Vue中mapbox地图的使用(一)](https://blog.csdn.net/yuelizhe4774/article/details/125975864)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Vue 面试题( 前端开发 + Vue + 面试题 + 准备)](https://download.csdn.net/download/weixin_41784475/88219148)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值