WebGIS-Editor
介绍
GIS 图层管理功能中一个重要的需求是对各种数据格式的支持,针对不同的数据文件格式可以通过添加文件功能导入到地图中进行展示,这里是对各个数据文件进行解析,统一转为geojson 格式,通过oenlayer api 添加到地图中。
访问地址:http://www.crlkcloud.com/umv-dev/
添加文件
可以支持添加 shp 文件、kml文件、wkt文件、geojson文件、gpx文件、csv文件。
其中csv格式空间数据属性 Geometry 值格式必须为wkt格式,否则无法对csv 格式进行解析。
代码实现
界面
代码编写
解析数据
通过文件选择按钮选择对应的文件格式,执行对应格式的转换方法进行转换
1、SHP 数据
这个用到了 shpjs 包,可以通过 npm i shpjs 进行安装;
shp文件需要打包成一个 zip文件。
import shp from 'shpjs'
async explainShpFile(file) {
const res = []
const buffer = await file.arrayBuffer()
try {
res.push(await shp(buffer))
return res
} catch (error) {
console.log(error)
}
}
2、CSV 文件
import { default as CSV } from 'csv-parse'
import WKT from 'terraformer-wkt-parser'
// csv file
async explainCsvFile(file) {
const res = []
const _data = { idx: undefined, index: undefined }
const text = await file.text()
try {
CSV.parse(text, {
cast: (value, context) => {
if (_data.idx === undefined || _data.idx !== context.records) {
_data.idx = context.records
}
if (value === 'Geometry') {
_data.index = context.index
return
}
if (_data.index === context.index) {
const geojson = WKT.parse(value)
res.push(geojson)
// console.log(geojson)
}
},
trim: true
})
return res
} catch (error) {
console.log(error)
}
}
3、KML 文件
import { default as KML } from 'kml-utils'
// kml file
async explainKmlFile(file) {
const res = []
const text = await file.text()
try {
const kmlDom = new DOMParser().parseFromString(text, 'text/xml')
res.push(KML.parse(kmlDom))
return res
} catch (error) {
console.log(error)
}
}
4、GeoJSON 文件
// geojson
async explainGeojsonFile(file) {
const res = []
const text = await file.text()
try {
res.push(JSON.parse(text))
return res
} catch (error) {
console.log(error)
}
}
5、WKT文件
import WKT from 'terraformer-wkt-parser'
// geojson
async explainGeojsonFile(file) {
const res = []
const text = await file.text()
try {
res.push(JSON.parse(text))
return res
} catch (error) {
console.log(error)
}
}
6、GPX文件
import { default as GPX } from 'gpxparser'
// gpx file
async explainGpxFile(file) {
const res = []
const text = await file.text()
try {
const gpx = new GPX()
gpx.parse(text)
res.push(gpx.toGeoJSON())
return res
} catch (error) {
console.log(error)
}
}
添加图层
openlayers 使用 ol/format/GeoJSON 接口,创建features
const GeoJSON = this._ol.format.GeoJSON
const feature = new GeoJSON({ featureProjection: "EPSG:4326" }).readFeatures(json)
const vectorLayer = new this._ol.layer.Vector({
source: new this._ol.source.Vector({
features: feature,
wrapX: false
}),
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
})
});
layer2.getLayers().push(vectorLayer)