1.读取shp文件
插件:shapefile
地址:https://github.com/mbostock/shapefile
代码:
1 import { open } from 'shapefile' // 解析shp文件 2 3 4 // 上传shp文件解析成geojson 5 getUploadGeojson(file, callback) { 6 const name = file.file.name 7 const reader = new FileReader() 8 const fileData = file.file.originFileObj 9 reader.readAsArrayBuffer(fileData) 10 reader.onload = function () { 11 // 定义geojson数组, 一个shp里会有多个面, 即有多个geometry 12 let geojsonArr = [] 13 open(this.result) 14 .then((source) => { 15 source.read().then(function log(result) { 16 if (result.done) { 17 // 读取完毕 18 // 合并geojson为一个featureCollection 19 const featureCollection = turf.featureCollection(geojsonArr) 20 callback(featureCollection) 21 return 22 } 23 24 const json = result.value 25 geojsonArr.push(json) 26 return source.read().then(log) 27 }) 28 }) 29 .catch((error) => console.error(error.stack)) 30 } 31 } 32 33 //调用 34 35 this.getUploadGeojson(file, (featureCollection) => { 36 console.log(featureCollection) 37 })
2.读取zip文件
注意:文件需完整
插件:shpjs
地址:GitHub - calvinmetcalf/shapefile-js: Convert a Shapefile to GeoJSON. Not many caveats.
代码:
import shp from 'shpjs' // 上传shp文件解析成geojson getUploadGeojson(file, callback) { const name = file.file.name const reader = new FileReader() const fileData = file.file.originFileObj reader.readAsArrayBuffer(fileData) reader.onload = function () { // eslint-disable-next-line prefer-const shp(this.result) .then(function (geojson) { return geojson }) .catch(function () { alert('文件信息不完整') }) } } //调用 同上面shp调用