Menu
快讀
  • 旅遊
  • 生活
    • 美食
    • 寵物
    • 養生
    • 親子
  • 娛樂
    • 動漫
  • 時尚
  • 社會
  • 探索
  • 故事
  • 科技
  • 軍事
  • 国际
快讀

postgis計算矢量切片

2021 年 3 月 11 日 甄比比

    沒寫錯,是使用postgis計算出來矢量切片。在這之前先准備一個數據:一個GIS數據表(本例中數據爲一百萬的點數據,坐標:4326),並在表中添加x,y字段,方便後面的數據篩選。sql中用到了

[ST_AsMVT](http://postgis.net/docs/ST_AsMVT.html)和[ST_AsMVTGeom](http://postgis.net/docs/ST_AsMVTGeom.html)。<br>

    本文中創建矢量切片很簡單,就是使用下方的一個sql,運行結果如下圖。接著寫一個矢量切片的http服務(參考[go-vtile-example](https://github.com/vicapow/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

“`

![准備的數據](https://user-gold-cdn.xitu.io/2018/3/22/1624db3e51f34542?w=1028&h=811&f=png&s=367275)

![sql查詢](https://user-gold-cdn.xitu.io/2018/3/22/1624db557468830d?w=1843&h=583&f=png&s=85103)

![前端展示](https://user-gold-cdn.xitu.io/2018/3/22/1624dc8a43973135?w=1919&h=893&f=png&s=173232)

![切片請求控制台截圖](https://user-gold-cdn.xitu.io/2018/3/22/1624dcf1071ea2cc?w=1886&h=740&f=png&s=123889)

“`

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>

“`

相關文章:

  • 便宜爆了!美妝護膚也要采辦年貨!低至三折買人氣好物,NOVELA新春大促閃亮登場!
  • 便宜爆了!美妝護膚也要采辦年貨!低至三折買人氣好物,NOVELA新春大促閃亮登場
  • 新加坡開放了!瘋狂美妝大促回來了!NOVELA會員節超低折扣+慷慨返券+驚喜贈品,美妝護膚好物買到手軟~還有多個寶藏品牌…
  • 放假就是要給你好價!超多大牌經典護膚品、超好聞的新品沙龍香水低至5折!
  • GSS終于回來了!美妝護膚狂歡購物節大牌全線低至2折!囤貨攻略來咯~
  • 喜迎新加坡國慶!國際大牌美妝立減57新幣!另有滿贈滿減!不容錯過的美妝護膚大促來啦~
遊戲

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

©2025 快讀 | 服務協議 | DMCA | 聯繫我們