-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
137 lines (113 loc) · 2.47 KB
/
map.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package petastatis
import (
"io"
sm "github.com/flopp/go-staticmaps"
"github.com/fogleman/gg"
"github.com/golang/geo/s2"
)
// StaticMapFunction .
type StaticMapFunction interface {
AddObject(sm.MapObject)
Render(io.Writer) error
}
// StaticMapOptions .
type StaticMapOptions struct {
center s2.LatLng
zoom int
width int
height int
attribution string
noCache bool
tileProvider sm.TileProvider
}
// StaticMapOption .
type StaticMapOption func(o *StaticMapOptions)
// Center .
func Center(center s2.LatLng) StaticMapOption {
return func(o *StaticMapOptions) {
o.center = center
}
}
// Zoom .
func Zoom(zoom int) StaticMapOption {
return func(o *StaticMapOptions) {
o.zoom = zoom
}
}
// Size .
func Size(width, height int) StaticMapOption {
return func(o *StaticMapOptions) {
o.width = width
o.height = height
}
}
// TextAttribution .
func TextAttribution(s string) StaticMapOption {
return func(o *StaticMapOptions) {
o.attribution = s
}
}
// TileProvier .
func TileProvider(p sm.TileProvider) StaticMapOption {
return func(o *StaticMapOptions) {
o.tileProvider = p
}
}
// NoTileCache .
func NoTileCache(v bool) StaticMapOption {
return func(o *StaticMapOptions) {
o.noCache = v
}
}
// staticMapFunction .
type staticMapFunction struct {
objects []sm.MapObject
options *StaticMapOptions
}
func (s *staticMapFunction) AddObject(o sm.MapObject) {
s.objects = append(s.objects, o)
}
func (s *staticMapFunction) Render(w io.Writer) error {
ctx := sm.NewContext()
ctx.SetTileProvider(sm.NewTileProviderOpenCycleMap()) // default
ctx.SetCenter(s.options.center)
ctx.SetZoom(s.options.zoom)
ctx.SetSize(s.options.width, s.options.height)
ctx.OverrideAttribution(s.options.attribution)
if s.options.noCache {
// set cache provide to nil
ctx.SetCache(nil)
}
for _, o := range s.objects {
ctx.AddObject(o)
}
// if custom tile provider is provided
if s.options.tileProvider != nil {
ctx.SetTileProvider(s.options.tileProvider)
}
// render
img, err := ctx.Render()
if err != nil {
return err
}
pngCtx := gg.NewContextForImage(img)
return pngCtx.EncodePNG(w)
}
// StaticMap .
func StaticMap(options ...StaticMapOption) StaticMapFunction {
// default options
opt := &StaticMapOptions{
center: s2.LatLngFromDegrees(0, 0),
zoom: 16,
width: 400,
height: 400,
}
// set override
for _, option := range options {
option(opt)
}
return &staticMapFunction{
objects: make([]sm.MapObject, 0),
options: opt,
}
}