cesium加载shp文件

文章介绍了如何使用CesiumVectorTile.js加载shp文件,包括直接引用、借助shapefile.js转换为geojson以及页面上传文件后转换加载的方法。同时,文中提供了读取shp和dbf文件,将其转换为geojson并在Cesium中显示的详细步骤。
摘要由CSDN通过智能技术生成

在这里插入图片描述

一、CesiumVectorTile.js加载shp文件

Cesium VectorTileImageryProvider 支持小数据量的geojson、shape文件矢量动态切片,实现贴地
下载CesiumVectorTile.js文件并在index.html中引入

<script src="./CesiumVectorTile.js"></script>

加载shp文件,shp文件同级目录下需要有dbf文件,prj文件,不可隐藏地球球体

var VectorTileImageryProvider = Cesium.VectorTileImageryProvider;

var worldLayer = null;
var worldProvider = new VectorTileImageryProvider({
  source: "./static/hubei.shp",
  defaultStyle: {
    outlineColor: "#02a9ff",
    lineWidth: 1,
    fill: false,
    tileCacheSize: 200,
    showMaker: false,
    showCenterLabel: true,
    fontColor: "#02a9ff",
    labelOffsetX: -10,
    labelOffsetY: -5,
    fontSize: 13,
    fontFamily: "黑体",
    centerLabelPropertyName: "NAME"
  },
  maximumLevel: 20,
  minimumLevel: 1,
  simplify: false
});
worldProvider.readyPromise.then(function () {
worldLayer = viewer.imageryLayers.addImageryProvider(worldProvider);
});

在这里插入图片描述

二、借助插件shapefile.js加载dbf和shp文件,转成geojson后加载

下载shapefile.js文件并引入

import * as shapefile from "./shapefile";

读取shp文件并生成geojson,加载到cesium中。
shp文件同级目录下需要有dbf文件。

const url = './static/hubei.shp'
const urlArr = url.split('.shp')
const dbfUrl = urlArr[0] + '.dbf'

this.createAndLoad(url, dbfUrl, { encoding: "utf-8" });
createAndLoad(shpData, dbfData, options) {
      const $this = this;
      var myFeatures = [];
      shapefile
        .open(shpData, dbfData, options)
        .then((source) =>
          source.read().then(function log(result) {
            if (result.done) {
              var _mGeoJson = {
                type: "FeatureCollection",
                features: myFeatures,
              };
              const layer = viewer.dataSources.add(
                Cesium.GeoJsonDataSource.load(_mGeoJson, {
                  clampToGround: false,
                  stroke: Cesium.Color.fromCssColorString("#02a9ff"), //new Cesium.Color(0/255, 0/255, 0/255, 0),
                  fill: new Cesium.Color(222/255, 216/255, 192/255, 0.3),
                })
              );
              viewer.zoomTo(layer);
              return;
            } else {
              var _result = result.value;
              var _curFeature = {
                type: _result.type,
                geometry: {
                  type: _result.geometry.type,
                  coordinates: _result.geometry.coordinates,
                },
                properties: _result.properties,
              };
              myFeatures.push(_curFeature);
              return source.read().then(log);
            }
          })
        )
        .catch((error) => console.error(error.stack));
    },

三、在页面直接上传shp文件和dbf文件后转换并加载

本地shp数据或者在线shp数据,将shp数据转化为geojson数据并下载,在cesium中加载。

loadShp4Server() {
  var _shpData, _dbfData;
  _shpData = document.getElementById("urlPath").value.trim();
  if (_shpData.indexOf(".shp") < 0) {
    console.log("注意:输入的shp服务端地址有误!");
    return;
  }
  _dbfData = _shpData.substr(0, _shpData.length - 3) + "dbf";
  this.CreateAndLoadShp(_shpData, _dbfData, { encoding: "utf-8" });
},
loadShp4Localhost() {
  const $this = this;
  var shpFile, dbfFile, _shpData, _dbfData;
  var filesSelect = Array.from(document.getElementById("_shpFile").files);
  if (filesSelect.length != 2) {
    console.log(
      "注意:所选择内容只能是一个图层的.shp和.dbf文件!"
    );
    return;
  }
  filesSelect.forEach((element) => {
    if (element.name.indexOf(".shp") > 0) {
      shpFile = element;
    } else if (element.name.indexOf(".dbf") > 0) {
      dbfFile = element;
    }
  });
  if (!shpFile || !dbfFile) {
    console.log(
      "注意:所选择内容必须包括同一个图层的.shp和.dbf文件!"
    );
    return;
  }
  var readShp = new FileReader();
  readShp.readAsArrayBuffer(shpFile, "UTF-8"); //读取文件的内容
  readShp.onload = function () {
    _shpData = this.result;
    var readDbf = new FileReader();
    readDbf.readAsArrayBuffer(dbfFile, "UTF-8"); //读取文件的内容
    readDbf.onload = function () {
      _dbfData = this.result;
      $this.CreateAndLoadShp(_shpData, _dbfData, { encoding: "utf-8" });
    };
  };
},
CreateAndLoadShp(shpData, dbfData, options) {
  const $this = this;
  var myFeatures = [];
  shapefile
    .open(shpData, dbfData, options)
    .then((source) =>
      source.read().then(function log(result) {
        if (result.done) {
          var _mGeoJson = {
            type: "FeatureCollection",
            features: myFeatures,
          };
          if ($this.boolDownload) {
            $this.funDownload(JSON.stringify(_mGeoJson), "default.geojson");
          }
          const layer = viewer.dataSources.add(
            Cesium.GeoJsonDataSource.load(_mGeoJson, {
              clampToGround: false,
              stroke: Cesium.Color.fromCssColorString("#02a9ff"), //new Cesium.Color(0/255, 0/255, 0/255, 0),
              fill: new Cesium.Color(222/255, 216/255, 192/255, 0.3),
            })
          );
          viewer.zoomTo(layer);
          return;
        } else {
          var _result = result.value;
          var _curFeature = {
            type: _result.type,
            geometry: {
              type: _result.geometry.type,
              coordinates: _result.geometry.coordinates,
            },
            properties: _result.properties,
          };
          myFeatures.push(_curFeature);
          return source.read().then(log);
        }
      })
    )
    .catch((error) => console.error(error.stack));
},
funDownload(content, filename) {
  var eleLink = document.createElement("a"); // 创建隐藏的可下载链接
  eleLink.download = filename;
  eleLink.style.display = "none";
  var blob = new Blob([content]); // 将字符内容转成blob
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink); // 点击触发
  eleLink.click();
  document.body.removeChild(eleLink); // 然后移除创建的元素
  console.log("下载完成");
},
getLocation() {
  let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  handler.setInputAction(function (event) {
    let earthPosition = viewer.scene.pickPosition(event.position);
    if (Cesium.defined(earthPosition)) {
      let cartographic = Cesium.Cartographic.fromCartesian(earthPosition);
      let lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(5);
      let lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(5);
      let height = cartographic.height.toFixed(2);
      console.log(earthPosition, {
        lon: lon,
        lat: lat,
        height: height,
      });
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值