forked from CrunchyData/pg_tileserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bounds.go
80 lines (71 loc) · 1.89 KB
/
bounds.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"fmt"
"math"
)
// Bounds represents a box in Web Mercator space
type Bounds struct {
Xmin float64 `json:"xmin"`
Ymin float64 `json:"ymin"`
Xmax float64 `json:"xmax"`
Ymax float64 `json:"ymax"`
}
func (b *Bounds) String() string {
return fmt.Sprintf("{Xmin:%g, Ymin:%g, Xmax:%g, Ymax:%g}",
b.Xmin, b.Ymin, b.Xmax, b.Ymax)
}
// SQL returns the SQL fragment to create this bounds in the database
func (b *Bounds) SQL() string {
return fmt.Sprintf("ST_MakeEnvelope(%g, %g, %g, %g, 3857)",
b.Xmin, b.Ymin,
b.Xmax, b.Ymax)
}
// Expand increases the size of this bounds in all directions, respecting
// the limits of the Web Mercator plane
func (b *Bounds) Expand(size float64) {
worldMin := -0.5 * worldMercWidth
worldMax := 0.5 * worldMercWidth
b.Xmin = math.Max(b.Xmin-size, worldMin)
b.Ymin = math.Max(b.Ymin-size, worldMin)
b.Xmax = math.Min(b.Xmax+size, worldMax)
b.Ymax = math.Min(b.Ymax+size, worldMax)
return
}
func (b *Bounds) sanitize() {
if b.Ymin < -90 {
b.Ymin = 90
}
if b.Ymax > 90 {
b.Ymax = 90
}
if b.Xmin < -180 {
b.Xmin = -180
}
if b.Xmax > 180 {
b.Xmax = 180
}
return
}
func fromMercator(x float64, y float64) (lng float64, lat float64) {
mercSize := worldMercWidth / 2.0
lng = x * 180.0 / mercSize
lat = 180.0 / math.Pi * (2.0*math.Atan(math.Exp((y/mercSize)*math.Pi)) - math.Pi/2.0)
return lng, lat
}
// Json returns the bounds in array for form consumption
// by Json formats that like it that way
func (b *Bounds) Json() []float64 {
s := make([]float64, 4)
s[0], s[1] = fromMercator(b.Xmin, b.Ymin)
s[2], s[3] = fromMercator(b.Xmax, b.Ymax)
return s
}
// Center returns the center of the bounds in array format
// for consumption by Json formats that like it that way
func (b *Bounds) Center() []float64 {
xc := (b.Xmin + b.Xmax) / 2.0
yc := (b.Ymin + b.Ymax) / 2.0
s := make([]float64, 2)
s[0], s[1] = fromMercator(xc, yc)
return s
}