openlayers 加载Shapefile文件

openlayers 加载Shapefile文件

Shapefile 是一种复杂的二进制格式,.shp(几何数据)、.shx(索引)、.dbf(属性数据)等多个文件组成,浏览器没有内置解析器,所以前端必须先把它转换成 Web 友好的格式(最常用的是 GeoJSON),再交给地图框架渲染。

  • 安装依赖
bash 复制代码
npm install shpjs
  • 工具文件:shpUtils.js
js 复制代码
import shp from 'shpjs';
import GeoJSON from 'ol/format/GeoJSON';
import { VectorSource } from 'ol/source';
import { Style, Fill, Stroke } from 'ol/style';

const waterStyle = new Style({
  fill: new Fill({ color: 'rgba(255, 0, 0, 1)' }),
  stroke: new Stroke({ color: 'red', width: 2 }),
});

export async function parseShpZip(fileOrBlob) {
  try {
    const buffer = await fileOrBlob.arrayBuffer();
    const parsedResult = await shp(buffer);

    let geojson = parsedResult.type ? parsedResult : Object.values(parsedResult)[0];

    const features = new GeoJSON().readFeatures(geojson, {});

    features.forEach((f) => f.setStyle(waterStyle));

    return features;
  } catch (err) {
    console.error('解析失败', err);
    throw err;
  }
}
  • 使用

.shp + .shx + .dbf + .prj 等打包成一个 .zip ,放到项目根目录的 public/ 文件夹下

js 复制代码
import { parseShpZip } from './shpUtils';
import {  Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';


async addShpLayer() {
      const url = '/图层数据.zip';
      const response = await fetch(url);
      const blob = await response.blob();

      const features = await parseShpZip(blob);

      const source = new VectorSource({ features });
      const layer = new VectorLayer({ source });
      this.map.addLayer(layer);

      source.on('featuresloadend', () => {
        const extent = source.getExtent();
        this.map.getView().fit(extent, { padding: [20, 20, 20, 20], duration: 500 });
      });
}
相关推荐
IT_陈寒几秒前
React hooks 闭包陷阱把我的状态吃掉了,原来问题出在这里
前端·人工智能·后端
壹方秘境1 分钟前
使用ApiCatcher在 iOS 上像修改 hosts 一样自定义域名解析
前端·后端·客户端
柳杉23 分钟前
可视化大屏设计器脚手架:从设计到交付的一站式方案
前端·three.js·数据可视化
铁皮饭盒36 分钟前
3行代码搞定页面截图,Bun.WebView真的简单
javascript
kyriewen14 小时前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
IT_陈寒14 小时前
Java的Date类又坑了我一次,改用时间戳真香
前端·人工智能·后端
山河木马15 小时前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
小林攻城狮15 小时前
使用 Transport 节流解决 Vercel AI SDK 流式渲染卡死问题
前端·react.js
前端缘梦15 小时前
告别 TS 运行时类型漏洞!Zod 完整入门实战教程(前端 / 全栈必备)
前端·react.js·全栈
the_answer15 小时前
Webpack vs Vite 深度对比分析
前端·webpack