没写错,是使用postgis计算出来矢量切片。在这之前先准备一个数据:一个GIS数据表(本例中数据为一百万的点数据,坐标:4326),并在表中添加x,y字段,方便后面的数据筛选。sql中用到了

ST_AsMVTST_AsMVTGeom

    本文中创建矢量切片很简单,就是使用下方的一个sql,运行结果如下图。接着写一个矢量切片的http服务(参考go-vtile-example,这个例子中矢量切片压缩率更高),并且使用mapbox进行前端展示(小贴士:sql中‘points’的字符串与渲染中mapbox里的source-layer一致).代码见最下方

SELECT ST_AsMVT(tile,'points') tile  FROM(
SELECT ST_AsMVTGeom(geom,ST_MakeEnvelope(100,10,125,22, 4326),4096, 0, true)
AS geom FROM grid20180322 )
AS tile where tile.geom is not null





package main

import
(
_ "github.com/lib/pq"
"database/sql"
"time"
"log"
"math"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
) func tilePathToXYZ(path string) (TileID, error) {
xyzReg := regexp.MustCompile("(?P<z>[0-9]+)/(?P<x>[0-9]+)/(?P<y>[0-9]+)")
matches := xyzReg.FindStringSubmatch(path)
if len(matches) == 0 {
return TileID{}, errors.New("Unable to parse path as tile")
}
x, err := strconv.ParseUint(matches[2], 10, 32)
if err != nil {
return TileID{}, err
}
y, err := strconv.ParseUint(matches[3], 10, 32)
if err != nil {
return TileID{}, err
}
z, err := strconv.ParseUint(matches[1], 10, 32)
if err != nil {
return TileID{}, err
}
return TileID{x: uint32(x), y: uint32(y), z: uint32(z)}, nil
}
type LngLat struct {
lng float64
lat float64
}
type TileID struct {
x uint32
y uint32
z uint32
} func tile2lon( x int, z int)(a float64) {
return float64(x) /math.Pow(2, float64(z)) * 360.0 - 180;
} func tile2lat( y int, z int)(a float64) {
n := math.Pi - (2.0 * math.Pi * float64(y)) / math.Pow(2, float64(z));
return math.Atan(math.Sinh(n))*180/math.Pi;
} func FloatToString(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', 6, 64)
} func loadData(xyz TileID)(a []byte){
ymax :=FloatToString(tile2lat(int(xyz.y), int(xyz.z)));
ymin := FloatToString(tile2lat(int(xyz.y+1), int(xyz.z)));
xmin := FloatToString(tile2lon(int(xyz.x), int(xyz.z)));
xmax := FloatToString(tile2lon(int(xyz.x+1), int(xyz.z)));
fmt.Println("ymax: ", ymax)
fmt.Println("ymin: ",ymin)
fmt.Println("xmin : ",xmin )
fmt.Println("xmax : ",xmax )
connStr := "dbname=xx user=xx password=xx host=localhost port=5433 sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
defer db.Close() err = db.Ping()
if err != nil {
panic(err)
} fmt.Println("Successfully connected!")
var tile []byte
s := []string{xmin,ymin,xmax,ymax}
maxmin:=strings.Join(s, ",")
s2 := []string{" where (x between", xmin,"and",xmax,") and ( y between",ymin,"and",ymax,")"}
wmaxmin:=strings.Join(s2, " ")
sql:="SELECT ST_AsMVT(tile,'points') tile FROM(SELECT ST_AsMVTGeom(w.geom,ST_MakeEnvelope("+maxmin+", 4326),4096, 0, true) AS geom FROM (select geom from grid20180322"+wmaxmin+") w) AS tile where tile.geom is not null"
rows1:= db.QueryRow(sql)
err1 := rows1.Scan(&tile)
if err1 != nil {
log.Fatal(err1)
}
fmt.Println(sql)
//defer rows1.Close()
return tile
}
func main(){
//t1 := time.Now()
mux := http.NewServeMux()
tileBase := "/tiles/"
mux.HandleFunc(tileBase, func(w http.ResponseWriter, r *http.Request) {
t2 := time.Now()
log.Printf("url: %s", r.URL.Path)
tilePart := r.URL.Path[len(tileBase):]
fmt.Println("tilePart: ", tilePart)
xyz, err := tilePathToXYZ(tilePart)
fmt.Println("xyz: ", xyz) if err != nil {
http.Error(w, "Invalid tile url", 400)
return
}
tile:=loadData(xyz) // All this APi to be requests from other domains.
w.Header().Set("Content-Type", "application/x-protobuf")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Write(tile)
elapsed2 := time.Since(t2) fmt.Println("耗时: ", elapsed2)
})
log.Fatal(http.ListenAndServe(":8081", mux))
}
<!DOCTYPE html>
<html> <head>
<meta charset='utf-8' />
<title>Add a third party vector tile source</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='mapbox-gl.js'></script>
<link href='mapbox-gl.css' rel='stylesheet' />
<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 = undenfined;
var tileset = 'mapbox.streets';
var map = new mapboxgl.Map({
container: 'map',
zoom: 12,
center: [109.898625809072612, 19.106708155556731],
style: 'mapbox://styles/mapbox/light-v9',
hash: false
}); map.on('load', function loaded() {
map.addSource('custom-go-vector-tile-source', {
type: 'vector',
tiles: ['http://localhost:8081/tiles/{z}/{x}/{y}']
});
map.addLayer({
id: 'background',
type: 'background',
paint: {
'background-color': 'white'
}
});
map.addLayer({
"id": "custom-go-vector-tile-layer",
"type": "circle",
"source": "custom-go-vector-tile-source",
"source-layer": "points",
paint: {
'circle-radius': {
stops: [
[8, 0.1],
[11, 0.5],
[15, 3],
[20, 20]
]
},
'circle-color': '#e74c3c',
'circle-opacity': 1
}
});
});
</script> </body> </html>

PostGIS计算矢量切片(一)--渲染数据的更多相关文章

  1. PostGIS计算矢量切片(二)--按值渲染

    方案背景     今年三月份写了一篇postgis计算矢量切片,参考了网上资料给出了一份很粗糙的相关方案(文章写的更粗糙).当时的方案中只能针对gis形状进行渲染,而不能用属性渲染.针对这个情况,本文 ...

  2. 开源方案搭建可离线的精美矢量切片地图服务-2.PostGIS+GeoServer矢量切片

    项目成果展示(所有项目文件都在阿里云的共享云虚拟主机上,访问地图可以会有点慢,请多多包涵). 01:中国地图:http://test.sharegis.cn/mapbox/html/3china.ht ...

  3. 开源方案搭建可离线的精美矢量切片地图服务-3.Mapbox个性化地图定制入门

    1.简介 mapbox是一家非常牛的公司,比如像特斯拉.DJI大疆创新.孤独星球.Airbnb.GitHub.Cisco.Snap.飞猪.Keep.Bosch这些在国内外各自领域中响当当的企业都是它的 ...

  4. 开源方案搭建可离线的精美矢量切片地图服务-4.Mapbox样式设计

    项目成果展示(所有项目文件都在阿里云的共享云虚拟主机上,访问地图可以会有点慢,请多多包涵). 01:中国地图:http://test.sharegis.cn/mapbox/html/3china.ht ...

  5. 开源方案搭建可离线的精美矢量切片地图服务-8.mapbox 之sprite大图图标文件生成(附源码)

    项目成果展示(所有项目文件都在阿里云的共享云虚拟主机上,访问地图可以会有点慢,请多多包涵). 01:中国地图:http://test.sharegis.cn/mapbox/html/3china.ht ...

  6. 开源方案搭建可离线的精美矢量切片地图服务-7.Arcgis Pro企业级应用

    1.前言 上篇讲.pbf字体库的时候说到我们使用的字体通过Arcgis Pro 生成,Arcgis Pro样式基于Mapbox做的矢量切片地图渲染.这篇主要讲一下Arcgis Pro矢量切片生成的的具 ...

  7. 开源方案搭建可离线的精美矢量切片地图服务-6.Mapbox之.pbf字体库

    项目成果展示(所有项目文件都在阿里云的共享云虚拟主机上,访问地图可以会有点慢,请多多包涵). 01:中国地图:http://test.sharegis.cn/mapbox/html/3china.ht ...

  8. 开源方案搭建可离线的精美矢量切片地图服务-5.Mapbox离线项目实现

    项目成果展示(所有项目文件都在阿里云的共享云虚拟主机上,访问地图可以会有点慢,请多多包涵). 01:中国地图:http://test.sharegis.cn/mapbox/html/3china.ht ...

  9. PIE SDK矢量唯一值渲染

    1. 功能简介 图层的唯一值渲染即是根据矢量图层的某一个数值字段的属性值,按照值的不同大小设置不同的显示符号.属性数值相等的所有要素归为同一种类,即同一符号. 2. 功能实现说明 2.1. 实现思路及 ...

随机推荐

  1. java内存分页计算

    介绍三个最常用的分页算法 First(感觉这个最简单实用) //总记录数int rows=21; //每页显示的记录数int pageSize=5; //页数int pageSum=(rows-1)/ ...

  2. 一次 HTTP 请求响应过程的完整解析

    因特网无疑是人类有史以来最伟大的设计,它互联了全球数亿台计算机.通讯设备,即便位于地球两端的用户也可在顷刻间完成通讯. 可以说『协议』是支撑这么一个庞大而复杂的系统有条不紊运作的核心,而所谓『协议』就 ...

  3. Java笔试题:给定一个ReadOnlyClass的对象roc,能否把这个对象的age值改成30?

    在Java笔试面试中,经常会遇到代码题,今天我们就来看一则Java代码笔试题. 有如下代码: Class ReadOnlyClass { private Integer age=20; public ...

  4. Array.find()和Array.findIndex()

    ES6新增的两个方法,根据回调函数返回作为判断依据,按照数组顺序进行遍历,符合条件(为真)时find()返回该值.findIndex()返回下标. 1.语法 arr.find(callback[, t ...

  5. [Swift]LeetCode38. 报数 | Count and Say

    The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 ...

  6. [Swift]LeetCode219. 存在重复元素 II | Contains Duplicate II

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j ...

  7. [Swift]LeetCode519. 随机翻转矩阵 | Random Flip Matrix

    You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all ...

  8. WebSocket(3)---实现一对一聊天功能

    实现一对一聊天功能 功能介绍:实现A和B单独聊天功能,即A发消息给B只能B接收,同样B向A发消息只能A接收. 本篇博客是在上一遍基础上搭建,上一篇博客地址:[WebSocket]---实现游戏公告功能 ...

  9. Python爬虫入门教程 13-100 斗图啦表情包多线程爬取

    斗图啦表情包多线程爬取-写在前面 今天在CSDN博客,发现好多人写爬虫都在爬取一个叫做斗图啦的网站,里面很多表情包,然后瞅了瞅,各种实现方式都有,今天我给你实现一个多线程版本的.关键技术点 aioht ...

  10. Java基础5:抽象类和接口

    本文主要介绍了抽象类和接口的特性和使用方法. 具体代码在我的GitHub中可以找到 https://github.com/h2pl/MyTech 文章首发于我的个人博客: https://h2pl.g ...