echarts-gl加载3D地图加载县/乡镇

环境

node :16.18.2

vue:vue3

echarts: 5.5

下包

npm指令直接下包

npm i echarts echarts-gl -S

调用

javascript 复制代码
import * as echarts from 'echarts';
import 'echarts-gl';

初始化函数

css 复制代码
// 引入地图贴图,一定要矩形,不然贴不全
import MapBg from '/@/assets/map/map_33.png';

const initChart = async () => {
  // 加载地图json数据
  const response = await fetch('/@/assets/map/xx.json');
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const mapData = await response.json();

  echarts.registerMap('xx地图', mapData);

  // 地图点位信息,value数组对应的是纬度,精度,高度
  const pointData = [    {name: "xx1", value: [119.42878, 31.465898, 30],address: '城北大道95号', dataArr: [{name: '装机量',value:45.32, unit: 'MW'}, {name: '容量',value:125.13, unit: 'MWh'}, {name: '功率',value:220, unit: 'W'}]},
    {name: "xx2", value: [119.496775, 31.455024, 30],address: '城北大道90号', dataArr: [{name: '装机量',value:145.32, unit: 'MW'}, {name: '容量',value:25.13, unit: 'MWh'}, {name: '功率',value:220, unit: 'W'}]},
    {name: "xx3", value: [119.476418, 31.469215, 30],address: '城北大道15号', dataArr: [{name: '装机量',value:425.32, unit: 'MW'}, {name: '容量',value:151.13, unit: 'MWh'}, {name: '功率',value:220, unit: 'W'}]},
  ]

  options1.value =  {
    tooltip:{
      show:true,
      padding: 0,
      backgroundColor: "transparent",
      extraCssText:`background: url('/@/assets/map/mapMark.png') 100% 100% no-repeat;background-size: cover;` , // 这里是点击点位之后对点位背景图的自定义图片
      // backgroundColor:'rgba(0,0,0,0)',
      borderColor:'rgba(0,0,0,0)',
      formatter: (params:any) => {// 自定义提示内容
        const html = `
                <div style="
                  background-size: 100% 100%;
                  width: 308px;
                  height: 219px;
                  padding: 30px 40px;
                  color: #FFF;
                  box-sizing: border-box;
                  text-align: left;
              ">
                       <h2 style="color: #67EFFF;font-weight: bold;text-align: left;font-size: 16px;margin-bottom: 0px">${params.name}</h2>
                       <div style="margin-top: 12px;display: flex;align-items: center;justify-content: start">
                          <div class="mapMarkTxt" style="color: #AAB0B5;">  <div class="mapMarkIcon"></div>${params.data.dataArr[0].name}</div>
                          <div class="mapMarkVal" style="margin-left: 6px;">${params.data.dataArr[0].value}</div>
                          <div class="mapMarkTxt" style="margin-left: 6px;">${params.data.dataArr[0].unit}</div>
                       </div>
                       <div style="margin-top: 12px;display: flex;align-items: center;justify-content: start">
                          <div class="mapMarkTxt" style="color: #AAB0B5;">  <div class="mapMarkIcon"></div>${params.data.dataArr[1].name}</div>
                          <div class="mapMarkVal" style="margin-left: 6px;">${params.data.dataArr[1].value}</div>
                          <div class="mapMarkTxt" style="margin-left: 6px;">${params.data.dataArr[1].unit}</div>
                       </div>
                       <div style="margin-top: 12px;display: flex;align-items: center;justify-content: start">
                          <div class="mapMarkTxt" style="color: #AAB0B5;">  <div class="mapMarkIcon"></div>${params.data.dataArr[2].name}</div>
                          <div class="mapMarkVal" style="margin-left: 6px;">${params.data.dataArr[2].value}</div>
                          <div class="mapMarkTxt" style="margin-left: 6px;">${params.data.dataArr[2].unit}</div>
                       </div>
                </div>`
        return html
      },
    },
    visualMap: {
      show: true,
      min: 0,
      max: 1000,
      calculable: true,
      inRange: {
        color: ['#2884db', '#244779']//气泡配色
      },
      textStyle:{
        color:'#fff'
      }
    },
    geo3D: {
      name: 'xx地图',
      type: 'map3D',
      map: 'xx地图',
      boxDepth: 120, //地图倾斜度
      regionHeight: 6, //地图厚度
      label: {
        show: true, //是否显示市
        color: "#fff", //文字颜色
        fontSize: 22, //文字大小
        fontFamily: '微软雅黑',
        backgroundColor: "rgba(0,0,0,0)", //透明度0清空文字背景
      },
      // environment: '/@/assets/map/map_bg.jpg', // 背景图片路径
      itemStyle: {
        opacity: 1, // 透明度
        borderWidth: 4, //分界线宽度
        borderColor: "#5B7187", //分界线颜色
      },
      groundplane: {
        show: false
      },
      roam: true, // 禁止拖动
      shading: 'realistic',
      // 真实感材质相关配置 shading: 'realistic'时有效
      realisticMaterial: {
        detailTexture: MapBg, // 纹理贴图
        textureTiling: 1, // 纹理平铺,1是拉伸,数字表示纹理平铺次数
        roughness: 0, // 材质粗糙度,0完全光滑,1完全粗糙
        metalness: 0, // 0材质是非金属 ,1金属
        roughnessAdjust: 0
      },
      viewControl:{
        projection: 'perspective',
        alpha: 60,  // 调整垂直旋转角度
        beta: 30,   // 调整水平旋转角度
        distance: 185,
        center:[5,-22,0],
        maxDistance :185, //最大的值 (默认400)
        minDistance :185,
      },
      label: {
        show: true, // 是否显示标签(地图区域名称)。
        color: "#fff",
        fontSize: 20,
        formatter: (e) => {
          return ` ${e.name} `;
        },
      },
      emphasis: {
        label: {
          show: true,
          color:'#fff',
        },
        itemStyle: {
          color: "#fff", // 白色就没有hover高亮
          opacity: 1,
          // color: null,
        },
      },
    },
    series: [
      {
        type: 'scatter3D',
        coordinateSystem: 'geo3D',
        data: pointData,
        symbol: 'pin',
        symbolSize: 25,
        itemStyle:{
          color:'purple',
          borderColor:'#fff',
          borderWidth:1
        },
        label:{
          show:false,
          formatter:'{b}',
          position:'bottom',
          textStyle:{
            color:'#000',
            backgroundColor:'#fff',
          }
        }
      }
    ]
  }
  
}

替换Echarts包下面Lib下的coord下的geo下的parseGeoJson解决乡镇地图无法加载

ini 复制代码
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/


/**
 * AUTO-GENERATED FILE. DO NOT MODIFY.
 */

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/**
 * Parse and decode geo json
 */
import * as zrUtil from 'zrender/lib/core/util.js';
import { GeoJSONLineStringGeometry, GeoJSONPolygonGeometry, GeoJSONRegion } from './Region.js';

function decode(json) {
  if (!json.UTF8Encoding) {
    return json;
  }

  var jsonCompressed = json;
  var encodeScale = jsonCompressed.UTF8Scale;

  if (encodeScale == null) {
    encodeScale = 1024;
  }

  var features = jsonCompressed.features;
  zrUtil.each(features, function (feature) {
    var geometry = feature.geometry;
    var encodeOffsets = geometry.encodeOffsets;
    var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
    // In this case this geometry is usually not encoded.

    if (!encodeOffsets) {
      return;
    }

    switch (geometry.type) {
      case 'LineString':
        geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
        break;

      case 'Polygon':
        decodeRings(coordinates, encodeOffsets, encodeScale);
        break;

      case 'MultiLineString':
        decodeRings(coordinates, encodeOffsets, encodeScale);
        break;

      case 'MultiPolygon':
        zrUtil.each(coordinates, function (rings, idx) {
          return decodeRings(rings, encodeOffsets[idx], encodeScale);
        });
    }
  }); // Has been decoded

  jsonCompressed.UTF8Encoding = false;
  return jsonCompressed;
}

function decodeRings(rings, encodeOffsets, encodeScale) {
  for (var c = 0; c < rings.length; c++) {
    rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  }
}

function decodeRing(coordinate, encodeOffsets, encodeScale) {
  var result = [];
  var prevX = encodeOffsets[0];
  var prevY = encodeOffsets[1];

  for (var i = 0; i < coordinate.length; i += 2) {
    var x = coordinate.charCodeAt(i) - 64;
    var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding

    x = x >> 1 ^ -(x & 1);
    y = y >> 1 ^ -(y & 1); // Delta deocding

    x += prevX;
    y += prevY;
    prevX = x;
    prevY = y; // Dequantize

    result.push([x / encodeScale, y / encodeScale]);
  }

  return result;
}

export default function parseGeoJSON(geoJson, nameProperty) {
  geoJson = decode(geoJson);
  return zrUtil.map(zrUtil.filter(geoJson.features, function (featureObj) {
    // Output of mapshaper may have geometry null
    // return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
    return featureObj.geometry && featureObj.properties && (
      // avoid length error if missing coordinates
      (featureObj.geometry.coordinates && featureObj.geometry.coordinates.length > 0)
      // allow GeometryCollection
      || (featureObj.geometry.geometries && featureObj.geometry.geometries.length > 0)
    )
  }), function (featureObj) {
    var properties = featureObj.properties;
    var geo = featureObj.geometry;
    var geometries = [];
    
    if (geo.type === 'Polygon') {
      var coordinates = geo.coordinates;
      geometries.push({
        type: 'polygon',
        // According to the GeoJSON specification.
        // First must be exterior, and the rest are all interior(holes).
        exterior: coordinates[0],
        interiors: coordinates.slice(1)
      });
    }
    
    if (geo.type === 'MultiPolygon') {
      
      var coordinates = geo.coordinates;
      zrUtil.each(coordinates, function (item) {
        if (item[0]) {
          geometries.push({
            type: 'polygon',
            exterior: item[0],
            interiors: item.slice(1)
          });
        }
      });
    }
    
    if (geo.type === 'GeometryCollection') {
      var geometries2 = geo.geometries;
      zrUtil.each(geometries2, function (geo) { // OR      zrUtil.each(geometries2, function (geo) {
        var coordinates = geo.coordinates;
        if (geo.type === 'Polygon') { // this is a full copy from above
          geometries.push({
            type: 'polygon',
            exterior: coordinates[0],
            interiors: coordinates.slice(1)
          });
        } // end full copy
      });
    }
    
    var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
    region.properties = properties;
    return region;
  });
}

展示效果

相关推荐
魏大帅。2 分钟前
Axios 的 responseType 属性详解及 Blob 与 ArrayBuffer 解析
前端·javascript·ajax
花花鱼8 分钟前
vue3 基于element-plus进行的一个可拖动改变导航与内容区域大小的简单方法
前端·javascript·elementui
k093312 分钟前
sourceTree回滚版本到某次提交
开发语言·前端·javascript
EricWang135833 分钟前
[OS] 项目三-2-proc.c: exit(int status)
服务器·c语言·前端
September_ning33 分钟前
React.lazy() 懒加载
前端·react.js·前端框架
web行路人43 分钟前
React中类组件和函数组件的理解和区别
前端·javascript·react.js·前端框架
超雄代码狂1 小时前
ajax关于axios库的运用小案例
前端·javascript·ajax
长弓三石1 小时前
鸿蒙网络编程系列44-仓颉版HttpRequest上传文件示例
前端·网络·华为·harmonyos·鸿蒙
小马哥编程1 小时前
【前端基础】CSS基础
前端·css
嚣张农民2 小时前
推荐3个实用的760°全景框架
前端·vue.js·程序员