index.vue 10.1 KB
<template>
  <!-- 原生方式,没有使用vue-echarts -->
  <n-space vertical>
    <n-spin :show="show">
      <div :style="`width:${w}px;height:${h}px;`" ref="map3DRef"></div>
    </n-spin>
  </n-space>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, PropType, toRefs, watch, reactive } from 'vue'
import * as echarts from 'echarts'
import { registerMap } from 'echarts/core'
import 'echarts-gl'
import config, { areaEnum, dataPointI, optionType, historyParentType, backMapLevel } from './config'
import { getGeoJsonMap } from '@/api/external/common'
import dataMaps from './data.json'

const props = defineProps({
  chartConfig: {
    type: Object as PropType<config>,
    required: true
  }
})

const backIcon = 'path://M853.333333 245.333333H245.333333l93.866667-93.866666c12.8-12.8 12.8-34.133333 0-46.933334-12.8-12.8-34.133333-12.8-46.933333 0l-145.066667 145.066667c-12.8 12.8-12.8 34.133333 0 46.933333l145.066667 145.066667c6.4 6.4 14.933333 10.666667 23.466666 10.666667s17.066667-4.266667 23.466667-10.666667c12.8-12.8 12.8-34.133333 0-46.933333L256 311.466667h597.333333c6.4 0 10.666667 4.266667 10.666667 10.666666v426.666667c0 6.4-4.266667 10.666667-10.666667 10.666667H170.666667c-17.066667 0-32 14.933333-32 32s14.933333 32 32 32h682.666666c40.533333 0 74.666667-34.133333 74.666667-74.666667V320c0-40.533333-34.133333-74.666667-74.666667-74.666667z'

const { w, h } = toRefs(props.chartConfig.attr)

const map3DRef = ref()

const show = ref(true)

const chartInstance = ref()

const toolBoxOption = ref({
  show: true,
  right: 110,
  top: 20,
  feature: {
    myFullButton: {
      show: false,
      title: '返回',
      icon: backIcon,
      iconStyle: {
        color: ''
      },
      onclick: () => handleBack()
    }
  }
})

const excludeCountryLevels = ['PROVINCE','CITY'] //如果从右侧配置选择全中国

const includeCityLevels = ['CITY'] //如果从右侧配置选择省份

//元组 优化if elseif else分支 隐藏返回图标
const backIconMappingLevels: any[][] =[
  [
    (levelStr:string)=>levelStr===areaEnum.COUNTRY,
    (level:string)=>excludeCountryLevels.includes(level),
    ()=>toolBoxOption.value.feature.myFullButton.show=true,
    ()=>toolBoxOption.value.feature.myFullButton.show=false
  ],
  [
    (levelStr:string)=>levelStr===areaEnum.PROVINCE,
    (level:string)=>includeCityLevels.includes(level),
    ()=>toolBoxOption.value.feature.myFullButton.show=true,
    ()=>toolBoxOption.value.feature.myFullButton.show=false
  ],
]


watch(
  () => props.chartConfig.option,
  (newData:optionType) => {
    const { iconColor, iconDistanceRight, iconDistanceTop, mapRegion } = newData
    const { saveSelect }=mapRegion
    const { levelStr }=saveSelect
    const findBackLevel = backIconMappingLevels.find((backLevelItem: backMapLevel[])=>backLevelItem[0](levelStr)) as backMapLevel[]
    if(findBackLevel){
      if(findBackLevel[0]){
        const findLevel = findBackLevel[1](saveLevelStr.level)
        if(findLevel)findBackLevel[2]()
        else findBackLevel[3]()
      }
    }
    toolBoxOption.value.feature.myFullButton.iconStyle.color = iconColor //返回图标颜色
    toolBoxOption.value.right = iconDistanceRight
    toolBoxOption.value.top = iconDistanceTop
  },
  {
    deep: true
  }
)

//追加echarts右上角自带toolbox
props.chartConfig.option = {
  ...props.chartConfig.option,
  ...{ toolbox: toolBoxOption.value }
}

//地图点击返回
const handleBack = async () => {
  stopWatch()
  if (props.chartConfig.option.drillingIn) {
    //如果是从右边配置里设置的,比如点击四川省,然后点击返回
    const savePopParent = saveHistoryParent.value.pop()
    let saveAdcode = savePopParent?.adcode as string | number
    saveLevelStr.level = savePopParent?.level as string
    if (!savePopParent) {
      saveAdcode = getParentAdcode(props.chartConfig.option.mapRegion.adcode)
      saveLevelStr.level = (regionMapParentArea as Recordable)[props.chartConfig.option.mapRegion.saveSelect.levelStr]
    }
    if (saveAdcode === 0) {
      saveAdcode = 'china'
      saveLevelStr.level = areaEnum.COUNTRY
    }
    const exist = await getGeojson(saveAdcode)
    const adcode = saveAdcode === 100000 ? 'china' : saveAdcode
    props.chartConfig.option.saveClickRegion.level = saveLevelStr.level
    if (exist) {
      //fix解决点击下钻返回后页面为空问题
      props.chartConfig.option.mapRegion.adcode = adcode
    }
  }
}

//地区上级对应配置
const regionMapParentArea = {
  PROVINCE: areaEnum.COUNTRY, //省份的上一级 中国
  CITY: areaEnum.PROVINCE, //城市的上一级 省份
  COUNTY: areaEnum.CITY, //县或者区的上一级 城市
  TOWN: areaEnum.COUNTY //镇的上一级 县或者区
}

//地图点击
const handleMap3DClick = async (params: Recordable) => {
  if (props.chartConfig.option.drillingIn) {
    const { name } = params
    saveGeojson.value?.features.forEach((item: Recordable) => {
      if (item.properties.name === name) {
        const level = item.properties.level.toUpperCase()
        const adcode = item.properties.adcode
        if (level === 'DISTRICT') return //下钻暂且不支持地区
        if (String(adcode).startsWith('15') && level === areaEnum.CITY) return //特殊处理地区码15开头的
        props.chartConfig.option.mapRegion.adcode = adcode
        props.chartConfig.option.saveClickRegion.level = level
        saveLevelStr.level = level
        handleDataPoint(adcode)
        saveHistoryParent.value.push({
          adcode: item.properties.parent.adcode,
          level: (regionMapParentArea as Recordable)[level]
        })
      }
    })
  }
}

const saveGeojson: Recordable = ref({}) // 保存geojson

const chinaDefaultRegionId = ref(100000) //如果是china则adcode为100000

const saveLevelStr = reactive<{level:historyParentType["level"]}>({
  // 地区级别
  level: ''
})

const saveHistoryParent = ref<historyParentType[]>([])

//动态注册地图
const getGeojson = (regionId: number | string) => {
  try {
    return new Promise<boolean>(resolve => {
      const { levelStr } = props.chartConfig.option.mapRegion.saveSelect //右侧配置项获取的行政级别
      getGeoJsonMap(
        regionId === 'china' ? chinaDefaultRegionId.value : regionId,
        !saveLevelStr.level ? levelStr : saveLevelStr.level //没有则获取右侧配置的行政级别
      ).then(res => {
        const { geoJson, name, code, level } = res.data
        const geoJsonFile = JSON.parse(geoJson)
        if (!geoJsonFile) return
        saveGeojson.value = geoJsonFile//保存一份服务端返回的geojson
        const nameChina = name === '中国' ? 'china' : name
        registerMap(level === areaEnum.COUNTRY ? nameChina : code, { geoJSON: geoJsonFile, specialAreas: {} })
        show.value = false
        resolve(true)
      })
    })
  } catch (error) {
    show.value = false
    console.error('注册地图出错', error)
    //注册出错则注册空的,不然在选择正确的adcode,则视图无法更新
    registerMap(props.chartConfig.option.mapRegion.adcode, { geoJSON: {} as any, specialAreas: {} })
  }
}

//异步时先注册空的 保证初始化不报错
registerMap(props.chartConfig.option.mapRegion.adcode, { geoJSON: {} as any, specialAreas: {} })

//传adcode 获取上级
const getParentAdcode = (adcode: number) => {
  let adcodeNum = 100000
  saveGeojson.value?.features.forEach((item: Recordable) => {
    if (item.properties.adcode === adcode) {
      adcodeNum = item.properties.parent.adcode
    }
  })
  return adcodeNum
}

watch(
  () => w.value,
  (value: number) => {
    chartInstance.value.resize({
      width: value + 'px',
      height: h.value + 'px'
    })
  }
)

const initMap = async () => {
  chartInstance.value = echarts.init(map3DRef.value)
  await nextTick()
  await getGeojson(props.chartConfig.option.mapRegion.adcode)
  await nextTick().then(() => {
    handleSetOption(chartInstance.value, props.chartConfig.option)
  })
  chartInstance.value.on('click', (e: Recordable) => {
    handleMap3DClick(e)
  })
}

// 手动触发渲染
const handleSetOption = (instance: any, option: Recordable) => {
  if (!instance) return
  try {
    instance.clear()
    instance.setOption(option)
  } catch (error) {
    console.error('触发渲染出错', error)
  }
}

onMounted(() => {
  initMap()
})

//处理数据标点
const handleDataPoint = (newData: string | number) => {
  if (newData === 'china') {
    props.chartConfig.option.dataset = dataMaps
    props.chartConfig.option.series.forEach((item: Recordable) => {
      if (item.type === 'scatter3D') {
        item.data = dataMaps
      }
    })
  } else {
    props.chartConfig.option.dataset = dataMaps.filter((item: dataPointI) => item.adcode === newData)
    props.chartConfig.option.series.forEach((item: Recordable) => {
      if (item.type === 'scatter3D') {
        item.data = dataMaps.filter((item: dataPointI) => item.adcode === newData)
      }
    })
  }
}

//监听地图展示区域发生变化
watch(
  () => `${props.chartConfig.option.mapRegion.adcode}`,
  async (newData: string | number) => {
    try {
      await getGeojson(newData)
      props.chartConfig.option.geo3D.map = newData
      props.chartConfig.option.series.forEach((item: Recordable) => {
        if (item.type === 'map3D') {
          item.map = newData
          item.data = props.chartConfig.option.dataset
        }
      })
      handleSetOption(chartInstance.value, props.chartConfig.option)
      handleDataPoint(newData)
    } catch (error) {
      console.log('展示区域发生变化出错', error)
    }
  },
  {
    immediate: true
  }
)

// 监听地图右侧配置项变化
const stopWatch = watch(
  props.chartConfig.option,
  async newData => {
    try {
      handleSetOption(chartInstance.value, newData)
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: true
  }
)

// 监听地图dataset配置项变化
watch(
  () => props.chartConfig.option.dataset,
  newData => {
    try {
      props.chartConfig.option.series.forEach((item: Recordable) => {
        if (item.type === 'map3D') {
          item.data = newData
        }
      })
      handleSetOption(chartInstance.value, props.chartConfig.option)
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: true
  }
)
</script>