利用 geobuf 实现 openlayers 加载矢量要素
我们经常遇到直接传输GIS数据到前端展示的时候,有时候数据量一稍微多点,传输速度就减慢,因为我们用于传输的json格式比较大。
为此,作者找了很多解决办法,在此博客中https://www.cnblogs.com/polong/p/11532450.html
,发现利用 Geobuf 对 GeoJSON数据压缩到协议缓冲区,实现快速传到前端
经过尝试,确实可以,本人尝试的代码如下:
服务端:
# 下面代码运行环境为 FastAPI
import pandas as pd
from sqlalchemy import create_engine
DEFAULT_DB_DRIVER = 'postgresql'
DEFAULT_DB_USER = 'postgres'
DEFAULT_DB_PWD = 'postgres'
DEFAULT_DB_HOST = 'localhost'
DEFAULT_DB_PORT = 5432
DEFAULT_DB_NAME = 'cu'
engine = create_engine(
f'{DEFAULT_DB_DRIVER}://{DEFAULT_DB_USER}:{DEFAULT_DB_PWD}@{DEFAULT_DB_HOST}:{DEFAULT_DB_PORT}/{DEFAULT_DB_NAME}')
@router.get("datasets/geobuf")
async def load_vector(name: str):
res = pd.read_sql_query(f"select st_asgeobuf(tb, 'geom') from (select fid, geom from {name} ) as tb",
con=engine).at[0, 'st_asgeobuf']
return Response(content=res.tobytes())
前端:
import axios
import Pbf from 'pbf'
import geobuf from 'geobuf'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import { GeoJSON } from 'ol/format'
async loadGeobuf ({ state, commit }, name) {
var res = await axios({
method: 'get',
url: `/datasets/geobuf?name=${'dg3'}`,
responseType: 'arraybuffer'
})
var geojson = geobuf.decode(new Pbf(obj.data))
var format = new GeoJSON()
var features = format.readFeatures(geojson, {
dataProjection: 'EPSG:4326'
})
var source = new VectorSource()
source.addFeatures(features)
var vectorLayer = new VectorLayer({
source: source
})
olMap.addLayer(vectorLayer) // olMap为实例化的openlayers的Map对象
}
参考资料:
https://github.com/mapbox/geobuf
https://github.com/mapbox/pbf