基于PostGIS实现本地矢量切片服务,通过mapboxgl来进行服务渲染

发布时间:2024年01月06日

在PG支持ST_AsMVT函数之前,如果要从PostGIS中生成矢量切片,需要借助地图服务软件来进行服务发布,如:GeoServer。从PostGIS2.4.0及以上版本后,可以使用ST_AsMVT聚合函数将基于MapBox VectorTile坐标空间的几何图形转换为MapBox VectorTile二进制矢量切片,从而实现不需要地图服务软件就能进行地图加载的功能。
所需软件

  • postgresql
  • postgis
    软件安装:
    略。(本文在具备postgresql、postgis软件环境下进行编写)。具体软件安装步骤,参考:https://www.cnblogs.com/alunzuishuai/p/16344904.html
    导入数据:
    安装PostGIS后会提供一个数据导入工具,可以将shapefile数据导入到指定数据库中。
    选择PostGIS Shapefile Import工具 ,输入用户密码,数据库地址,连接数据库,导入数据。
    在这里插入图片描述
    连接成功之后点击 Add File 导入shapefile文件到数据库。
    注意:1.文件名和文件路径不要是中文,否则导入可能会失败。
    2.将SRID编码设置为4326。
    在这里插入图片描述
    服务端实现:
    Dirt-Simple PostGIS HTTP API 介绍:
    Dirt-Simple PostGIS HTTP API 是一种向应用程序公开地理空间功能的简单方法。它通过 HTTP 接受简单的请求,并将 JSON、JSONP 或 protobuf(Mapbox Vector Tile)返回给请求者。
    仓库地址:https://github.com/tobinbradley/dirt-simple-postgis-http-api
    下载后安装依赖并运行。
    修改config目录中index.json文件,将db改为本地postgresql数据库地址
    在这里插入图片描述
    在这里插入图片描述
    修改前:
    “db”: “postgres://user:password@server/database”,
    修改后:
    “db”: “postgres://postgres:123456@localhost:5432/test”,

使用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>
**加载效果:**

在这里插入图片描述

本文整理转载来自:https://zhuanlan.zhihu.com/p/349849542?utm_id=0

文章来源:https://blog.csdn.net/STANDBYF/article/details/135410779
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。