GeoJSON与GeoBuf互相转换

时间:2019-09-22
本文章向大家介绍GeoJSON与GeoBuf互相转换,主要包括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

原文地址:https://www.cnblogs.com/jyughynj/p/11567569.html