echarts结合高德地图插件展示中国地图

<template>
  <div class="home">
    <div class="echarts-map" ref="echartsMap"></div>
  </div>
</template>

<script>
// @ is an alias to /src
import * as echarts from 'echarts'
// import 'echarts/map/china'
// import mapJson from '@/static/china.json'
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'HomeView',
  data () {
    return {
      echartInstance: null,
      opts: null,
      district: null,
      mapData: [],
      cityCode: null,
      cityName: null,
      geoJsonData: null
    }
  },
  created () {
  },
  mounted () {
    this.mapInit()
  },
  methods: {
    // 使用高德地图获取边界数据
    mapInit () {
      AMapLoader.load({
        key: '', // 需要在高德地图申请的Key
        plugins: ['AMap.DistrictSearch'], // 需要用到的插件
        AMapUI: { // 重点就是这个
          version: '1.0',
          plugins: []
          // plugins: ['misc/PathSimplifier', 'overlay/SimpleMarker']// SimpleMarker设置自定义图标,PathSimplifier轨迹展示组件
        }
      }).then(AMap => {
        // console.log(AMapUI)
        this.opts = {
          subdistrict: 1, // 返回下一级行政区
          showbiz: false // 最后一级返回街道信息
        }
        this.district = new AMap.DistrictSearch(this.opts)// 注意:需要使用插件同步下发功能才能这样直接使用
        this.district.search('中国', (status, result) => {
          if (status === 'complete') {
            this.getData(result.districtList[0], '', 100000)
          }
        })
      })
    },
    getData (data, level, adcode) { // 处理获取出来的边界数据
      const subList = data.districtList
      if (subList) {
        // 街道级别是不能返回边界数据polyline的,乡镇街道级别返回的adcode是所属区县的adcode。
        const curlevel = subList[0].level
        if (curlevel === 'street') { // 为了配合echarts地图区县名称显示正常,这边街道级别数据需要特殊处理
          const mapJsonList = this.geoJsonData.features
          const mapJson = {}
          for (const i in mapJsonList) {
            if (mapJsonList[i].properties.name === this.cityName) {
              mapJson.features = [].concat(mapJsonList[i])
            }
          }
          this.mapData = []
          // 这个mapData里包含每个区域的code、名称、对应的等级,实现第三步功能时能用上
          this.mapData.push({ name: this.cityName, value: Math.random() * 100, level: curlevel })
          this.initMap(this.cityName, mapJson)
          this.geoJsonData = mapJson
          return
        }

        // 街道级以上的数据处理方式
        this.mapData = []
        for (let i = 0, l = subList.length; i < l; i++) {
          const name = subList[i].name
          const cityCode = subList[i].adcode
          // 这个mapData里包含每个区域的code、名称、对应的等级,实现第三步功能时能用上
          this.mapData.push({
            name: name,
            value: Math.random() * 100,
            cityCode: cityCode,
            level: curlevel
          })
        }
        this.loadMapData(adcode)
      }
    },
    // 获取边界数据
    loadMapData (areaCode) {
      AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
        // 创建一个实例
        const districtExplorer = window.districtExplorer = new DistrictExplorer({
          eventSupport: true, // 打开事件支持
          map: this.map
        })

        districtExplorer.loadAreaNode(areaCode, (error, areaNode) => {
          if (error) {
            console.error(error)
            return
          }
          const mapJson = {}
          // 特别注意这里哦,如果查看过正常的geojson文件,都会发现,文件都是以features 字段开头的,所以这里要记得加上
          mapJson.features = areaNode.getSubFeatures()
          this.geoJsonData = mapJson
          this.initMap(this.cityName, mapJson)
        })
      })
    },
    // 随机获取值
    randomData () {
      return Math.round(Math.random() * 500)
    },
    // 初始化地图
    initMap (mapName, data) {
      const dom = this.$refs.echartsMap
      echarts.registerMap('mapName', { geoJSON: data }) // echarts版本过高,所以使用json注册数据
      // echarts.registerMap(mapName, { ...data, type: 'FeatureCollection' })
      this.echartInstance = echarts.init(dom)
      const boxHeight = this.echartInstance.getHeight()
      const boxWidth = this.echartInstance.getWidth()
      const layoutSize = boxWidth < boxHeight ? boxWidth * 0.95 : boxHeight * 0.95
      const optionChinaMap = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderColor: 'rgba(50,50,50,0.7)',
          textStyle: {
            color: '#fff'
          },
          formatter: (params) => {
            const val = params.value ? params.value : 0
            return params.name + ': ' + parseInt(val) + ' 小区'
          }
        },
        // 地图标题
        title: {
          text: '中国',
          subtext: '',
          x: 'center'
        },
        legend: {
          orient: 'horizontal', // 图例的排列方向
          textStyle: { color: '#333' },
          x: 'left', // 图例的位置
          y: '30',

          data: ['全国数据']
        },
        geo: {
          show: true,
          map: 'mapName',
          zoom: 1, // 地图大小
          roam: true, // 是否开启鼠标缩放和平移漫游
          z: 5,
          // top: '20%', // 组件距离容器的距离
          layoutCenter: [boxWidth / 2, boxHeight / 2],
          layoutSize: layoutSize,
          itemStyle: { // 地图区域的多边形 图形样式
            areaColor: '#0D3060',
            borderType: 'dotted',
            borderColor: 'rgba(80,190,250,.5)',
            borderWidth: 1
            // normal: { // 是图形在默认状态下的样式
            //   label: {
            //     show: true,
            //     textStyle: { color: 'rgb(249, 249, 249)' }
            //   }
            // }
          },
          emphasis: { // 是图形在高亮状态下的样式,比如在鼠标悬浮或者图例联动高亮时
            // label: { show: true },
            label: {
              color: '#FFC76A'
            },
            itemStyle: {
              color: '#c7f3fe'
            }
          }
        },

        // visualMap: { // 颜色的设置  dataRange
        //   textStyle: { color: '#333' },
        //   x: 'left',
        //   y: 'bottom',
        //   splitList: [
        //     { start: 1500 }, { start: 900, end: 1500 },
        //     { start: 310, end: 1000 }, { start: 200, end: 300 },
        //     { start: 50, end: 200 }, { start: 0, end: 50 }
        //   ],
        //   // text:['高','低'],// 文本,默认为数值文本
        //   // color: ['#65A2D9', '#E09107', '#A3E00B']
        //   color: ['#5475f5', '#9feaa5', '#3FA7FF', '#66E0E3', '#FFDC5E', '#9fb5ea']
        // },
        visualMap: {
          show: true,
          min: 0,
          max: 1000,
          left: 'left',
          top: 'bottom',
          text: ['高', '低'], // 文本,默认为数值文本
          calculable: true,
          seriesIndex: [0],
          outOfRange: {
            color: '#0D3060'
          },
          inRange: {
            color: ['#60E7FF', '#20A6F6'] // 渐变
          },
          textStyle: {
            color: '#333'
          }
        },
        roamController: { // 控制地图的上下左右放大缩小
          show: true,
          x: 'right',
          mapTypeControl: {
            china: true
          }
        },
        series: [
          {
            name: '全国数据',
            type: 'map',
            data: this.mapData,
            geoIndex: 0
          }
        ]
      }
      this.echartInstance.setOption(optionChinaMap)
      this.addMapEvent()
    },
    // 添加地图交互
    addMapEvent () {
      const myChart = echarts.getInstanceByDom(this.$refs.echartsMap)
      myChart.off('mouseover')
      myChart.on('mouseover', function (params) {
        if (!params.value) {
          myChart.dispatchAction({
            type: 'downplay',
            geoIndex: [0, 1, 2, 3]
          })
        }
      })
      myChart.off('click')
      myChart.on('click', (params) => {
        console.log('click', params)
        if (params.data.level === 'street') return// 此处的params.data为this.mapData里的数据
        this.cityCode = params.data.cityCode
        this.cityName = params.data.name
        // 行政区查询
        // 按照adcode进行查询可以保证数据返回的唯一性
        this.district.search(this.cityCode, (status, result) => {
          if (status === 'complete') {
            this.getData(result.districtList[0], params.data.level, this.cityCode)// 这个getData函数在前面已经定义过了
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.echarts-map{
  min-width: 600px;
  min-height: 500px;
}
</style>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值