通过Shapefile读取shp文件并渲染

需要引入<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”

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值