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 });
      });
}
相关推荐
油丶酸萝卜别吃3 小时前
utils.js 说明文档
开发语言·javascript·ecmascript
zyplayer-doc5 小时前
VuePress类静态文档站和动态知识库怎么选:两种技术路线的适用场景
javascript·人工智能·后端·安全·智能手机
紫禁玄科6 小时前
Shai-Hulud:npm生态的自我复制蠕虫风暴
前端·npm·node.js
东风破_7 小时前
后端API没写好,前端难道干等着吗?
前端
用户938515635077 小时前
从前后端分离到前端接口工程:React + MockJS + Vite 解析
前端·后端·全栈
用户938515635077 小时前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformers.js 全链路实战(三)
前端·react.js·typescript
excel7 小时前
当前端行情变差,我们为什么还要坚持?
前端
鸿是江边鸟,曾是心上人8 小时前
快速搭建HTTPS本地开发环境
前端
To_OC8 小时前
写了 5 个表单 Demo 后,我终于彻底搞懂了 React 受控与非受控组件
前端·react.js·前端框架
Sterting8 小时前
第9课 Vue Router 路由
前端·vue.js