GeoJSON與GeoBuf互相轉換


GeoJSON格式通常比較大,網頁需要較長時間加載,可以使用GeoBuf進行壓縮。

使用GeoBuf有很多好處:結構緊湊、文件小、方便編碼和解碼、能適用各種GeoJSON等等。

使用:

1.安裝 geobuf 和 pbf

1 npm install geobuf
2 npm install pbf

2.對GeoJSON編碼

1 let buffer = geobuf.encode(featureCollection, new Pbf())

說明:需要引入geobuf 和 pbf,

          featureCollection為GeoJSON

3.把GeoBuf寫入文件

1 let buffer = geobuf.encode(featureCollection, new Pbf()) // 對GeoJSON編碼
2 // 使用node寫入文件 需要先引入'fs'庫
3 fs.writeFile('./data/lamp.geobuf.bpf', buffer, function(error){
4     if(error){
5         console.info('geobuf error')
6     }else {
7         console.info('geobuf ok')
8     }
9 })

4.對GeoBuf解碼

1 axios.get('./data/lamp.geobuf.bpf', {
2     responseType: 'arraybuffer' // note: responseType must be 'arraybuffer'
3 }).then((function (res) {
4     let data = res.data
5     let geojson = geobuf.decode(new Pbf(data)) // 對GeoBuf解碼
6     console.info(JSON.stringify(geojson))
7 }))

注意:讀取GeoBuf是responseType必須是“arraybuffer”

看一下文件大小:只有大約1/5了,效果很明顯吶!

 

 完整應用案例請參考:

https://github.com/shiyuan598/common-tools.git
 
        
 
         
        

參考文檔:

https://github.com/mapbox/geobuf

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM