其他分享
首页 > 其他分享> > MapBox加载矢量瓦片

MapBox加载矢量瓦片

作者:互联网

基于python + Postgresql MVT+ MapBox 加载矢量瓦片的方法

from rest_framework.views import APIView
from rest_framework.response import Response
import psycopg2.extras
DB_HOST = ''
DB_PORT = 5432
DB_USERNAME = ''
DB_PASSWORD = ''
DB_NAME = ''
class PostgresMapApiView(APIView):
    def get(self, request, table_name, z, x, y):
        columns = ',' + request.GET.get('columns', '') if request.GET.get('columns', None) else ''
        id_column = ',' + request.GET.get('id_column', '') if request.GET.get('id_column', None) else ''
        conn = psycopg2.connect(host=DB_HOST, port=DB_PORT, user=DB_USERNAME, password=DB_PASSWORD, database=DB_NAME)
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        sql = " WITH mvtgeom as ( SELECT  ST_AsMVTGeom ( ST_Transform(geom, 3857),ST_TileEnvelope(" + z + "," + x + ", " + y + ")) as geom " + columns + id_column + " FROM " + table_name + ",(SELECT ST_SRID(geom) AS srid FROM " + table_name + " LIMIT 1) a WHERE ST_Intersects(geom,ST_Transform(ST_TileEnvelope(" + z + ", " + x + ", " + y + "),srid))) SELECT ST_AsMVT(mvtgeom.*, '" + table_name + "', 4096, 'geom' ) AS mvt from mvtgeom;"
        cursor.execute(sql)
        r = cursor.fetchone()
        try:
            from django.http.response import StreamingHttpResponse
            response = StreamingHttpResponse(r)
            response['Content-Type'] = 'application/x-protobuf'
            return response
        except:
            return Response(formatResponse(code=404))
map.on('load', function () {
        map.addLayer({
          "id": "mapillary-point",
          type: 'symbol',
          "source": {
            "type": "vector",
            "tiles": ["http://192.168.10.113:8000/demo/postgres/【表名】/{z}/{x}/{y}?columns=【需要的列名】"],
            "minzoom": 6,
          },
          'source-layer': '【表名】',
          "glyphs": "font/{fontstack}/{range}.pbf",
          "layout": {
            "text-size": 13.3333,
            "text-field": "{【展示的字段名称】}",
            "text-optional": true,
          },
          "paint": {
            "text-color": "#ffffff", // 文本的颜色(可选,默认值为 #000000)
            "text-halo-color": "rgba(0,0,0,0)", // 文本的光晕颜色(可选,默认值为 rgba(0,0,0,0))
          }
        })
        map.addLayer({
          "id": "mapillary-polygon",
          type: 'fill',
          "source": {
            "type": "vector",
            "tiles": ["http://192.168.10.113:8000/demo/postgres/【表名】/{z}/{x}/{y}?id_column=需要的列名】"],
            "minzoom": 6,
          },
          'source-layer': '【表名】',
          'paint': {
            'fill-color': '#fff000',
            'fill-opacity': 0.3,
            "fill-outline-color": "#000000",
          }
        }, 'mapillary-point')
        map.on('click', 'mapillary-polygon', (e) => {
          console.log(e.features[0])
        })
      });

 

标签:get,text,MapBox,DB,ST,瓦片,id,columns,加载
来源: https://www.cnblogs.com/yvyao/p/15637320.html