需要引入<script type="text/javascript" src="../js/Shapefile.js"></script>
const GeoJSONFormat = new ol.format.GeoJSON()
function fileChange(param) {
const self = this
const reader = new FileReader()
const fileData = param// param.file
// 读取文件
if (!/.shp/ig.test(fileData.name)) { // 不是.shp文件得情况(json\geojson)
reader.readAsText(fileData)// 将文件读取为文本
} else {
reader.readAsArrayBuffer(fileData)// 将文件读取为二进制编码
}
reader.onload = function (evt) {
const shparray = evt.target.result
if (!/.shp/ig.test(fileData.name)) { // 不是.shp文件得情况(json\geojson)
const json = JSON.parse(shparray)
const features = []
const feature = GeoJSONFormat.readFeature(json.features[0])
features.push(feature)
drawLayer.getSource().addFeatures(features)
self.map.addLayer(drawLayer)
} else {
// 定义geojson数组, 一个shp里会有多个面, 即有多个geometry
const geojsonArr = []
shapefile.open(shparray).then((source) => {
source.read().then(function log(result) {
if (result.done) {
// 解析完成
console.log(geojsonArr)
// 可以在地图绘制展示geojsonArr
return
}
const json = result.value
geojsonArr.push(json)
const features = []
const feature = GeoJSONFormat.readFeature(json)
features.push(feature)
drawLayer.getSource().addFeatures(features)
self.map.addLayer(drawLayer)
return source.read().then(log)
})
})
.catch((error) => {
console.error(error.stack)
this.$message.error('读取shp文件失败')
})
}
}
}
下载Shapefile.js源文件:https://unpkg.com/shapefile@0.6 下载完成后修改源文件中的数据编码类型:“windows-1252”改为“gb2312”