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 });
      });
}
相关推荐
To_OC9 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮10 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny10 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹10 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny10 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC10 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn11 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
REDcker11 小时前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜11 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康12 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端