在PG支持ST_AsMVT函数之前,如果要从PostGIS中生成矢量切片,需要借助地图服务软件来进行服务发布,如:GeoServer。从PostGIS2.4.0及以上版本后,可以使用ST_AsMVT聚合函数将基于MapBox VectorTile坐标空间的几何图形转换为MapBox VectorTile二进制矢量切片,从而实现不需要地图服务软件就能进行地图加载的功能。
所需软件
使用npm run start 运行程序,访问localhost:3000查看API文档
其中 /v1/mvt/{table}/{z}/{x}/{y} 就是生成矢量切片服务所用到的api
前端实现:
前端使用mapboxgl来进行服务渲染。
注意:矢量切片数据源的路径,参考api。
示例:‘http://127.0.0.1:3000/v1/mvt/fxq_hxd_tzq_pg/{z}/{x}/{y}?geom_column=geom’
如我这示例中要加载 fxq_hxd_tzq_pg 图层
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display a map on a webpage</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = '你的token';
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [104.44406, 30.30933],
zoom: 12,
hash: true,
maxZoom: 30
});
map.on('load', function() {
map.addLayer({
id: 'fxq_hxd_tzq_pg',
source: {
type: 'vector',
tiles: ['http://127.0.0.1:3000/v1/mvt/fxq_hxd_tzq_pg/{z}/{x}/{y}?geom_column=geom'],
},
'source-layer': 'fxq_hxd_tzq_pg',
type: 'fill',
paint: {
'fill-color': '#088',
'fill-outline-color': 'rgb(215,25,28)'
}
})
});
</script>
</body>
</html>
**加载效果:**