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 });
      });
}
相关推荐
一个心烑1 小时前
Layui结合springboot读取返回值,前端展示简单示例
前端·spring boot·layui
亿元程序员1 小时前
手工拼豆有风险?手把手教你开发个电子版的
前端
wuxianda10301 小时前
苹果App上架4.3a问题3天解决方案汇报总结
开发语言·javascript·uni-app·ecmascript·ios上架·苹果上架
hhhhhh_we1 小时前
再定义“皮肤人格”:从Baumann 16型分型到预颜美历的AI时序人格
前端·图像处理·人工智能·python·aigc
琹箐1 小时前
今天吃什么干什么随机生成
javascript·css·css3
鹏程十八少1 小时前
10. 2026金三银四 Android 组件化 & ARouter 面试杀手锏:33 道高频题 + 答案 + 流程图 + 源码,资深工程师必刷
前端·后端·面试
yqcoder1 小时前
CSS 布局双雄:浮动 (Float) vs 绝对定位 (Absolute) 深度解析
前端·css
朝阳391 小时前
react【实战】首页 -- 白天/黑夜主题切换(含组件封装)
前端·react.js·前端框架
卷Java1 小时前
ReAct范式实战:让Agent学会边想边做
javascript·react.js·大模型·llm·ecmascript·multi-agent