项目场景:
openlayer 请求加载远程.shp文件
安装引入shpjs
:需要用到shpjs 这个库去解析请求过来的文件
npm i shpjs
import shp from 'shpjs'; // shp转geoJson
解析方法:
用shp.parseShp方法解析buffer文件, 返回值promise类型
const loadSHPData = async url => {
const response = await fetch(url);
const buffer = await response.arrayBuffer();
return shp.parseShp(buffer);
};
完整代码:
import { onMounted } from 'vue';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { Style, Circle, Fill, Stroke } from 'ol/style';
// 创建图层
const polygonLayer = new VectorLayer({
source: new VectorSource(),
zIndex: 10,
style: new Style({
fill: new Fill({
color: 'blue',
}),
}),
});
const initPolygonLayer = () => {
const url = `你的http请求地址`;
loadSHPData(url).then(res => {
// 这里对coord进行转换
const data = handleData(res);
// 一般返回的是geojson格式的,但是接口返回的是geometry数组 需要手动转为geojson格式
const features = new GeoJSON().readFeatures({
type: 'FeatureCollection',
features: data.map(geometry => ({
type: 'Feature',
geometry,
})),
});
polygonLayer.getSource().addFeatures(features);
const extent = polygonLayer.getSource().getExtent();
map.getView().fit(extent);
map.addLayer(polygonLayer);
});
};
// 处理数据 将32651转为4326
const handleData = res => {
return res.map(i => {
const arr = i.coordinates[0].map(j => {
return transform(j, 'EPSG:32651', 'EPSG:4326');
});
return {
type: i.type,
coordinates: [arr],
};
});
};
onMounted(() => {
initPolygonLayer();
});