ECharts 根据屏幕变化更改大小地图

本文介绍如何使用ECharts库根据屏幕尺寸变化调整地图大小。通过监听窗口resize事件,动态设置地图容器宽度,确保在不同屏幕尺寸下地图能够自适应显示。示例代码中展示了如何加载ECharts地图组件,以及初始化和更新图表的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!--这是地图-->
<template>
  <div>
    <div ref="contractRateChart02" class="mar-0-auto pull-left" :style="{width:'95%',height: charHeightTop+'px'}"></div>
    <Modal v-model="showNoModal" title="提示">
      <p style="color:#F54C44;fontSize:14px;">暂未统计到此地区家庭医生签约服务数据</p>
      <div slot="footer">
        <Button type="primary" @click="okClick">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {getJson} from '@/api/api'
  import { mapState , mapGetters , mapActions} from 'vuex'

  // 引入echar
  // 引入基本模板
  let echarts = require('echarts/lib/echarts')
  // 引入饼图。
  require('echarts/lib/chart/pie')
  // 引入柱状图组件
  require('echarts/lib/chart/bar')
  // 引入折线图。
  require('echarts/lib/chart/line')
  // 引入地图。
  require('echarts/lib/chart/map')

  require('echarts/map/js/china.js') // 引入中国地图数据

  // import hebei from '../../../../assets/json/hebei/hebei.json'

  // 引入提示框和title组件
  require('echarts/lib/component/tooltip')
  require('echarts/lib/component/title')
  require('echarts/lib/component/toolbox')
  require('echarts/lib/component/legend')

  import {homeProvinceGetHeatMapData} from '@/api/api'

  let contractRateChartInit02;
  export default {
    name: 'char-top-row-map',
    data(){
      return {
        showNoModal:false,
        areaPinyin:'hebei',
        pinyin:'',
        cityData:[],
        screenWidth: document.body.clientWidth,   // 这里是给到了一个默认值 (这个很重要)
      }
    },
    props: [
      'charHeightTop',
      'bindData'
    ],
    computed:{
      ...mapState([
        'sysUser'
      ]),
      //选中的年份
      queryYear(){
        return this.bindData.queryYear
      },
      //是否为贫困人口
      povertyPeople(){
        return this.bindData.povertyPeople
      },
      //机构代码编号
      querySysCode(){
        return this.bindData.querySysCode
      },
      //区域代码编号
      queryAreaCode(){
        return this.bindData.queryAreaCode
      }
    },
    created(){

    },
    watch :{
      queryYear(){
        this.searchAjax();
        // console.log('年份发生了变化'+this.queryYear);
      },
      //是否为贫困人口
      povertyPeople(){
        this.searchAjax();
        // console.log('是否为贫困人口发生了变化'+this.povertyPeople);
      },
      //机构代码编号
      querySysCode(){
        this.searchAjax();
        // console.log('机构代码编号发生了变化'+this.querySysCode);
      },
      //区域代码编号
      queryAreaCode(){
        // console.log('区域代码编号发生了变化'+this.queryAreaCode);
        this.searchAjax();
      },

      charHeightTop(){
        // console.log(this.charHeightTop);
      },
      screenWidth (val) {
        if (!this.timer) {
          this.screenWidth = val
          this.timer = true
          let that = this
          setTimeout(function () {
            that.init()
            that.timer = false
          }, 400)
        }
      }
    },
    mounted (){
      this.searchAjax();
      const that = this;
      window.addEventListener("resize", function() {
        return (() => {
          window.screenWidth= document.body.clientWidth;
          that.screenWidth= window.screenWidth;
        })();
      });
      this.$nextTick(() => {
        getJson(`static/json/hebei/pinyin.json`).then(res => {
          this.pinyin = res.data;
//           this.drawLine02();
        });
//         echarts.registerMap('hebei', hebei);
//         this.drawLine02();
      })
    },
    methods: {
      init(){
        contractRateChartInit02.resize();
      },
      searchAjax(){
        this.searchData={
          querySysCode:this.querySysCode,
          queryYear:this.queryYear,
          queryAreaCode:this.queryAreaCode
        }
        homeProvinceGetHeatMapData(this.searchData).then(res => {
          if (res.code == 0) {
            // console.log(res.data);
            for(let i=0;i<res.data.length;i++){
              res.data[i].name=res.data[i].areaName;
              res.data[i].value=res.data[i].signPersonNumber;
            }
            this.cityData=res.data;
            // console.log(this.cityData);
            this.drawLine02();
          }else{
            this.cityData=[];
            this.drawLine02();
            this.$Message.error(res.message);
          }
        });
      },
      drawLine02(){
        let queryAreaCode=this.queryAreaCode;
        if(this.queryAreaCode==""){
          queryAreaCode=this.sysUser.areaCode;
        }
        for(let i=0;i<this.pinyin.features.length;i++){
//          console.log(this.pinyin.features.length);
          if(this.pinyin.features[i].code==queryAreaCode){
            this.areaPinyin=this.pinyin.features[i].pinyin;
          }
        }
        // 上面的图
        getJson(`static/json/hebei/${this.areaPinyin}.json`).then(res => {
          echarts.registerMap('hebei', res.data);
          // 基于准备好的dom,初始化echarts实例
          contractRateChartInit02 = echarts.init(this.$refs.contractRateChart02)

          contractRateChartInit02.setOption({
            backgroundColor:'transparent',
            // 添加地图
            tooltip: {
              trigger: 'item',
              formatter: function loadData(result) {//回调函数,参数params具体格式参加官方API
                if(result.data==undefined){
                  return '此地区暂无数据';
                }else{
                  return result.data.areaName + ' <br/> '+ '入驻机构:' + result.data.orgNumber + ' <br/> '+ '组建家签团队:' + result.data.teamNumber + ' <br/> '+ '入驻服务人员:' + result.data.doctorNumber + ' <br/> '+ '签约总人数:' + result.data.signPersonNumber + ' <br/> '+ '履约总人数:' + result.data.performePersonNumber ;
                }
              }
              // formatter: '{b}<br/>{c}'
            },
            // legend: {
            //   orient: 'vertical',
            //   y: 'bottom',
            //   x: 'right',
            //   selectedMode:false,//取消图例上的点击事件
            //   textStyle: {
            //     color: '#fff'
            //   }
            // },
            visualMap: {
              min: 800,
              max: 50000,
              text:['高','低'],
              realtime: false,
              calculable: true,
              textStyle:{
                color:'#999'
              },
              inRange: {
                color: ['#80C6FF','#33A3FF', '#008CFF','#0073E6']
              }
            },
            series: [{
              type: 'map',
              map: 'hebei',//要和echarts.registerMap()中第一个参数一致
              mapLocation: {
                y: 60
              },
              layoutCenter: ['50%', '50%'],
              layoutSize: '100%',
              itemStyle: {
                normal: {
                  areaColor: '#C1BBBB',
                  borderColor: '#fff',
                  borderWidth: '3'
                },
                // emphasis: {
                //   areaColor: '#030734'
                // }
              },
              label: {
                normal: {
                  show: true,
                  color: 'white'
                },
                emphasis: {
                  show: true,
                  color: 'white'
                }
              },
              data: this.cityData,
            }]

          });
          let that=this;
          contractRateChartInit02.on('click', function (paramss) {
            if(paramss.data==undefined){
              that.showNoModal=true;
            }else{
              if(paramss.data.areaCode.length>4){
                let areaCode=paramss.data.areaCode;
                let params=encodeURI(JSON.stringify({ areaCode : areaCode}));
                that.$router.push({ name: 'chartsMainBottom',  params: { params}});
                // that.$router.push({ name: 'chartsMainBottom',  params: { areaCode:that.queryAreaCode}});
              }else{
                for(let i=0;i<that.pinyin.features.length;i++){
                  if(that.pinyin.features[i].name==paramss.name){
                    // console.log("发送请求");
                    // that.$router.push({ name:'chartsMain',params: {areaLabel: that.pinyin.features[i].name}});
                    that.$emit('changeAreaCode', paramss.data.areaCode); //第一个参数是父组件中v-on绑定的自定义回调方法,第二个参数为传递的参数
                  }
                }
              }
            }


          })
        });
      },
      okClick(){
        this.showNoModal=false;
      }
    }
  }
</script>

<style scoped>

</style>
### ECharts 地图提示框配置 在 ECharts 中,可以通过 `tooltip` 组件来设置地图上的提示框行为。此组件允许自定义显示的内容、样式以及交互方式。 对于地图类型的图表而言,在初始化选项时加入 `tooltip` 字段可以控制其表现形式: ```javascript const option = { tooltip: { trigger: 'item', // 触发类型,默认数据项触发 formatter: '{b}<br/>{c}' // 自定义浮层内容格式器函数或字符串模板 }, ... }; ``` 当鼠标悬停于某个区域之上时会弹出包含该地区名 `{b}` 和数值 `{c}` 的信息窗[^1]。 如果遇到提示框超出容器边界的情况,则需调整定位逻辑以确保良好用户体验。一种常见做法是在回调里动态计算并修正偏移量: ```javascript tooltip: { confine: true, // 是否将 tooltip 框限制在图表区域内 enterable: false, transitionDuration: 0.2, position: function (point, params, dom, rect, size) { var viewWidth = window.innerWidth; var viewHeight = window.innerHeight; let x = point[0]; let y = point[1]; if ((viewWidth - x) < size.contentSize[0]) { x -= size.contentSize[0]; // 如果右侧空间不足则左移至左侧展示 } if ((viewHeight - y) < size.contentSize[1]) { y -= size.contentSize[1]; // 底部空间不够就往上挪动 } return [x,y]; } } ``` 上述代码片段通过监听窗口尺寸变化实时更新最佳显示位置,并利用条件判断防止溢出屏幕边缘[^3]。 另外值得注意的是,为了提高可读性和美观度还可以进一步美化这些浮动标签的外观属性,比如更改背景颜色、字体大小等参数;同时也可以考虑引入 HTML 片段支持更复杂的布局结构[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值