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 });
      });
}
相关推荐
和平宇宙21 分钟前
AI笔记005. hermes-DeepSeek V4 Pro, 128K上下文引发的探索
前端·人工智能·笔记
IT_陈寒35 分钟前
Redis持久化这个坑,我爬了一整天才出来
前端·人工智能·后端
naildingding1 小时前
3-ts接口 Interface
前端·typescript
mONESY1 小时前
JavaScript 栈、队列、数组与链表核心知识点总结
javascript·面试
小小前端仔LC1 小时前
Node.js + LangChain + React:搭建个人知识库(六)- “吃什么”项目实战:从700+菜谱入库到Taro H5端JSON渲染
前端·后端
ZengLiangYi1 小时前
TypeScript 项目配置:tsconfig、ESM、路径别名
javascript·typescript·aigc
晓13131 小时前
【Cocos Creator 3.x】篇——第二章 入门
前端·javascript·游戏引擎
想要成为糕糕手1 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
程序员黑豆2 小时前
AI全栈开发之Java:怎么配置Java环境变量
前端·后端·ai编程
xiaofeichaichai2 小时前
React Hooks
前端·javascript·react.js