forked from flopp/go-staticmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
671 lines (568 loc) · 18.5 KB
/
context.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
// Copyright 2016, 2017 Florian Pigorsch. All rights reserved.
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package sm (~ static maps) renders static map images from OSM tiles with markers, paths, and filled areas.
package sm
import (
"errors"
"image"
"image/color"
"image/draw"
"log"
"math"
"github.com/fogleman/gg"
"github.com/golang/geo/s1"
"github.com/golang/geo/s2"
)
// Context holds all information about the map image that is to be rendered
type Context struct {
width int
height int
hasZoom bool
zoom int
hasCenter bool
center s2.LatLng
hasBoundingBox bool
boundingBox s2.Rect
background color.Color
objects []MapObject
overlays []*TileProvider
userAgent string
tileProvider *TileProvider
cache TileCache
overrideAttribution *string
result RenderResult
}
// NewContext creates a new instance of Context
func NewContext() *Context {
t := new(Context)
t.width = 512
t.height = 512
t.hasZoom = false
t.hasCenter = false
t.hasBoundingBox = false
t.background = nil
t.userAgent = ""
t.tileProvider = NewTileProviderOpenStreetMaps()
t.cache = NewTileCacheFromUserCache(0777)
return t
}
// SetTileProvider sets the TileProvider to be used
func (m *Context) SetTileProvider(t *TileProvider) {
m.tileProvider = t
}
// SetCache takes a nil argument to disable caching
func (m *Context) SetCache(cache TileCache) {
m.cache = cache
}
// SetUserAgent sets the HTTP user agent string used when downloading map tiles
func (m *Context) SetUserAgent(a string) {
m.userAgent = a
}
// SetSize sets the size of the generated image
func (m *Context) SetSize(width, height int) {
m.width = width
m.height = height
}
// SetZoom sets the zoom level
func (m *Context) SetZoom(zoom int) {
m.zoom = zoom
m.hasZoom = true
}
// SetCenter sets the center coordinates
func (m *Context) SetCenter(center s2.LatLng) {
m.center = center
m.hasCenter = true
}
// SetBoundingBox sets the bounding box
func (m *Context) SetBoundingBox(bbox s2.Rect) {
m.boundingBox = bbox
m.hasBoundingBox = true
}
// SetBackground sets the background color (used as a fallback for areas without map tiles)
func (m *Context) SetBackground(col color.Color) {
m.background = col
}
// AddMarker adds a marker to the Context
//
// Deprecated: AddMarker is deprecated. Use the more general AddObject.
func (m *Context) AddMarker(marker *Marker) {
m.AddObject(marker)
}
// ClearMarkers removes all markers from the Context
func (m *Context) ClearMarkers() {
filtered := []MapObject{}
for _, object := range m.objects {
switch object.(type) {
case *Marker:
// skip
default:
filtered = append(filtered, object)
}
}
m.objects = filtered
}
// AddPath adds a path to the Context
//
// Deprecated: AddPath is deprecated. Use the more general AddObject.
func (m *Context) AddPath(path *Path) {
m.AddObject(path)
}
// ClearPaths removes all paths from the Context
func (m *Context) ClearPaths() {
filtered := []MapObject{}
for _, object := range m.objects {
switch object.(type) {
case *Path:
// skip
default:
filtered = append(filtered, object)
}
}
m.objects = filtered
}
// AddArea adds an area to the Context
//
// Deprecated: AddArea is deprecated. Use the more general AddObject.
func (m *Context) AddArea(area *Area) {
m.AddObject(area)
}
// ClearAreas removes all areas from the Context
func (m *Context) ClearAreas() {
filtered := []MapObject{}
for _, object := range m.objects {
switch object.(type) {
case *Area:
// skip
default:
filtered = append(filtered, object)
}
}
m.objects = filtered
}
// AddCircle adds an circle to the Context
//
// Deprecated: AddCircle is deprecated. Use the more general AddObject.
func (m *Context) AddCircle(circle *Circle) {
m.AddObject(circle)
}
// ClearCircles removes all circles from the Context
func (m *Context) ClearCircles() {
filtered := []MapObject{}
for _, object := range m.objects {
switch object.(type) {
case *Circle:
// skip
default:
filtered = append(filtered, object)
}
}
m.objects = filtered
}
// AddObject adds an object to the Context
func (m *Context) AddObject(object MapObject) {
m.objects = append(m.objects, object)
}
// ClearObjects removes all objects from the Context
func (m *Context) ClearObjects() {
m.objects = nil
}
// AddOverlay adds an overlay to the Context
func (m *Context) AddOverlay(overlay *TileProvider) {
m.overlays = append(m.overlays, overlay)
}
// ClearOverlays removes all overlays from the Context
func (m *Context) ClearOverlays() {
m.overlays = nil
}
// OverrideAttribution sets a custom attribution string (or none if empty)
//
// Pay attention you might be violating the terms of usage for the
// selected map provider - only use the function if you are aware of this!
func (m *Context) OverrideAttribution(attribution string) {
m.overrideAttribution = &attribution
}
// Attribution returns the current attribution string - either the overridden
// version (using OverrideAttribution) or the one set by the selected
// TileProvider.
func (m *Context) Attribution() string {
if m.overrideAttribution != nil {
return *m.overrideAttribution
}
return m.tileProvider.Attribution
}
func (m *Context) determineBounds() s2.Rect {
r := s2.EmptyRect()
for _, object := range m.objects {
r = r.Union(object.Bounds())
}
return r
}
func (m *Context) determineExtraMarginPixels() (float64, float64, float64, float64) {
maxL := 0.0
maxT := 0.0
maxR := 0.0
maxB := 0.0
if m.Attribution() != "" {
maxB = 12.0
}
for _, object := range m.objects {
l, t, r, b := object.ExtraMarginPixels()
maxL = math.Max(maxL, l)
maxT = math.Max(maxT, t)
maxR = math.Max(maxR, r)
maxB = math.Max(maxB, b)
}
return maxL, maxT, maxR, maxB
}
func (m *Context) determineZoom(bounds s2.Rect, center s2.LatLng) int {
b := bounds.AddPoint(center)
if b.IsEmpty() || b.IsPoint() {
return 15
}
tileSize := m.tileProvider.TileSize
margin := 0.0
w := (float64(m.width) - 2.0*margin) / float64(tileSize)
h := (float64(m.height) - 2.0*margin) / float64(tileSize)
minX := (b.Lo().Lng.Degrees() + 180.0) / 360.0
maxX := (b.Hi().Lng.Degrees() + 180.0) / 360.0
minY := (1.0 - math.Log(math.Tan(b.Lo().Lat.Radians())+(1.0/math.Cos(b.Lo().Lat.Radians())))/math.Pi) / 2.0
maxY := (1.0 - math.Log(math.Tan(b.Hi().Lat.Radians())+(1.0/math.Cos(b.Hi().Lat.Radians())))/math.Pi) / 2.0
dx := maxX - minX
for dx < 0 {
dx = dx + 1
}
for dx > 1 {
dx = dx - 1
}
dy := math.Abs(maxY - minY)
zoom := 1
for zoom < 30 {
tiles := float64(uint(1) << uint(zoom))
if dx*tiles > w || dy*tiles > h {
return zoom - 1
}
zoom = zoom + 1
}
return 15
}
// determineCenter computes a point that is visually centered in Mercator projection
func (m *Context) determineCenter(bounds s2.Rect) s2.LatLng {
latLo := bounds.Lo().Lat.Radians()
latHi := bounds.Hi().Lat.Radians()
yLo := math.Log((1+math.Sin(latLo))/(1-math.Sin(latLo))) / 2
yHi := math.Log((1+math.Sin(latHi))/(1-math.Sin(latHi))) / 2
lat := s1.Angle(math.Atan(math.Sinh((yLo + yHi) / 2)))
lng := bounds.Center().Lng
return s2.LatLng{Lat: lat, Lng: lng}
}
func (m *Context) determineZoomCenter() (int, s2.LatLng, error) {
bounds := m.determineBounds()
if m.hasBoundingBox && !m.boundingBox.IsEmpty() {
center := m.determineCenter(m.boundingBox)
return m.determineZoom(m.boundingBox, center), center, nil
} else if m.hasCenter {
if m.hasZoom {
return m.zoom, m.center, nil
}
return m.determineZoom(bounds, m.center), m.center, nil
} else if !bounds.IsEmpty() {
center := m.determineCenter(bounds)
if m.hasZoom {
return m.zoom, center, nil
}
return m.determineZoom(bounds, center), center, nil
}
return 0, s2.LatLngFromDegrees(0, 0), errors.New("cannot determine map extent: no center coordinates given, no bounding box given, no content (markers, paths, areas) given")
}
// Transformer implements coordinate transformation from latitude longitude to image pixel coordinates.
type Transformer struct {
zoom int
numTiles float64 // number of tiles per dimension at this zoom level
tileSize int // tile size in pixels from this provider
pWidth, pHeight int // pixel size of returned set of tiles
pCenterX, pCenterY int // pixel location of requested center in set of tiles
tCountX, tCountY int // download area in tile units
tCenterX, tCenterY float64 // tile index to requested center
tOriginX, tOriginY int // bottom left tile to download
pMinX, pMaxX int
proj s2.Projection
}
// Transformer returns an initialized Transformer instance.
func (m *Context) Transformer() (*Transformer, error) {
zoom, center, err := m.determineZoomCenter()
if err != nil {
return nil, err
}
return newTransformer(m.width, m.height, zoom, center, m.tileProvider.TileSize), nil
}
func newTransformer(width int, height int, zoom int, llCenter s2.LatLng, tileSize int) *Transformer {
t := new(Transformer)
t.zoom = zoom
t.numTiles = math.Exp2(float64(t.zoom))
t.tileSize = tileSize
// mercator projection from -0.5 to 0.5
t.proj = s2.NewMercatorProjection(0.5)
// fractional tile index to center of requested area
t.tCenterX, t.tCenterY = t.ll2t(llCenter)
ww := float64(width) / float64(tileSize)
hh := float64(height) / float64(tileSize)
// origin tile to fulfill request
t.tOriginX = int(math.Floor(t.tCenterX - 0.5*ww))
t.tOriginY = int(math.Floor(t.tCenterY - 0.5*hh))
// tiles in each axis to fulfill request
t.tCountX = 1 + int(math.Floor(t.tCenterX+0.5*ww)) - t.tOriginX
t.tCountY = 1 + int(math.Floor(t.tCenterY+0.5*hh)) - t.tOriginY
// final pixel dimensions of area returned
t.pWidth = t.tCountX * tileSize
t.pHeight = t.tCountY * tileSize
// Pixel location in returned image for center of requested area
t.pCenterX = int((t.tCenterX - float64(t.tOriginX)) * float64(tileSize))
t.pCenterY = int((t.tCenterY - float64(t.tOriginY)) * float64(tileSize))
t.pMinX = t.pCenterX - width/2
t.pMaxX = t.pMinX + width
return t
}
// ll2t returns fractional tile index for a lat/lng points
func (t *Transformer) ll2t(ll s2.LatLng) (float64, float64) {
p := t.proj.FromLatLng(ll)
return t.numTiles * (p.X + 0.5), t.numTiles * (1 - (p.Y + 0.5))
}
// LatLngToXY transforms a latitude longitude pair into image x, y coordinates.
func (t *Transformer) LatLngToXY(ll s2.LatLng) (float64, float64) {
x, y := t.ll2t(ll)
x = float64(t.pCenterX) + (x-t.tCenterX)*float64(t.tileSize)
y = float64(t.pCenterY) + (y-t.tCenterY)*float64(t.tileSize)
offset := t.numTiles * float64(t.tileSize)
if x < float64(t.pMinX) {
for x < float64(t.pMinX) {
x = x + offset
}
} else if x >= float64(t.pMaxX) {
for x >= float64(t.pMaxX) {
x = x - offset
}
}
return x, y
}
// Rect returns an s2.Rect bounding box around the set of tiles described by Transformer.
func (t *Transformer) Rect() (bbox s2.Rect) {
// transform from https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Go
invNumTiles := 1.0 / t.numTiles
// Get latitude bounds
n := math.Pi - 2.0*math.Pi*float64(t.tOriginY)*invNumTiles
bbox.Lat.Hi = math.Atan(0.5 * (math.Exp(n) - math.Exp(-n)))
n = math.Pi - 2.0*math.Pi*float64(t.tOriginY+t.tCountY)*invNumTiles
bbox.Lat.Lo = math.Atan(0.5 * (math.Exp(n) - math.Exp(-n)))
// Get longtitude bounds, much easier
bbox.Lng.Lo = float64(t.tOriginX)*invNumTiles*2.0*math.Pi - math.Pi
bbox.Lng.Hi = float64(t.tOriginX+t.tCountX)*invNumTiles*2.0*math.Pi - math.Pi
return bbox
}
// Render actually renders the map image including all map objects (markers, paths, areas)
func (m *Context) Render() (image.Image, error) {
zoom, center, err := m.determineZoomCenter()
if err != nil {
return nil, err
}
return m.renderWithZoomAndCenter(zoom, center)
}
func (m *Context) renderWithZoomAndCenter(zoom int, center s2.LatLng) (image.Image, error) {
m.result = RenderResult{
Zoom: zoom,
Center: center,
}
tileSize := m.tileProvider.TileSize
trans := newTransformer(m.width, m.height, zoom, center, tileSize)
img := image.NewRGBA(image.Rect(0, 0, trans.pWidth, trans.pHeight))
gc := gg.NewContextForRGBA(img)
if m.background != nil {
draw.Draw(img, img.Bounds(), &image.Uniform{m.background}, image.Point{}, draw.Src)
}
bounds := m.determineBounds()
leftX, bottomY := trans.LatLngToXY(bounds.Lo())
rightX, topY := trans.LatLngToXY(bounds.Hi())
left, top, right, bottom := m.getBoundaryMargins()
if !bounds.IsEmpty() && zoom > 0 {
widthWithMargins := (rightX + right) - (leftX - left)
heightWithMargins := (bottomY + bottom) - (topY - top)
if widthWithMargins > float64(m.width) || heightWithMargins > float64(m.height) {
return m.renderWithZoomAndCenter(zoom-1, center)
}
}
// fetch and draw tiles to img
layers := []*TileProvider{m.tileProvider}
if m.overlays != nil {
layers = append(layers, m.overlays...)
}
for _, layer := range layers {
if err := m.renderLayer(gc, zoom, trans, tileSize, layer); err != nil {
return nil, err
}
}
// draw map objects
for _, object := range m.objects {
object.Draw(gc, trans)
}
// crop image
croppedImg := image.NewRGBA(image.Rect(0, 0, int(m.width), int(m.height)))
startCropX := trans.pCenterX - int(m.width)/2
startCropY := trans.pCenterY - int(m.height)/2
if !bounds.IsEmpty() && int(leftX-left) < startCropX {
m.result.XOffset = startCropX - int(leftX-left)
startCropX -= m.result.XOffset
}
if !bounds.IsEmpty() && int(topY-top) < startCropY {
m.result.YOffset = startCropY - int(topY-top)
startCropY -= m.result.YOffset
}
draw.Draw(croppedImg, image.Rect(0, 0, int(m.width), int(m.height)),
img, image.Point{startCropX, startCropY},
draw.Src)
// draw attribution
attribution := m.Attribution()
if attribution == "" {
return croppedImg, nil
}
_, textHeight := gc.MeasureString(attribution)
boxHeight := textHeight + 4.0
gc = gg.NewContextForRGBA(croppedImg)
gc.SetRGBA(0.0, 0.0, 0.0, 0.5)
gc.DrawRectangle(0.0, float64(m.height)-boxHeight, float64(m.width), boxHeight)
gc.Fill()
gc.SetRGBA(1.0, 1.0, 1.0, 0.75)
gc.DrawString(attribution, 4.0, float64(m.height)-4.0)
return croppedImg, nil
}
func (m *Context) getBoundaryMargins() (float64, float64, float64, float64) {
var top, right, bottom, left float64
bounds := m.determineBounds()
epsilon := 1e-6
for _, object := range m.objects {
isSameTopPoint := math.Abs(object.Bounds().Hi().Lat.Degrees()-bounds.Hi().Lat.Degrees()) < epsilon
isSameRightPoint := math.Abs(object.Bounds().Hi().Lng.Degrees()-bounds.Hi().Lng.Degrees()) < epsilon
isSameBottomPoint := math.Abs(object.Bounds().Lo().Lat.Degrees()-bounds.Lo().Lat.Degrees()) < epsilon
isSameLeftPoint := math.Abs(object.Bounds().Lo().Lng.Degrees()-bounds.Lo().Lng.Degrees()) < epsilon
marginLeft, marginTop, marginRight, marginBottom := object.ExtraMarginPixels()
if isSameTopPoint && marginTop > top {
top = marginTop
}
if isSameRightPoint && marginRight > right {
right = marginRight
}
if isSameBottomPoint && marginBottom > bottom {
bottom = marginBottom
}
if isSameLeftPoint && marginLeft > left {
left = marginLeft
}
}
return left, top, right, bottom
}
// RenderWithTransformer actually renders the map image including all map objects (markers, paths, areas).
// The returned image covers requested area as well as any tiles necessary to cover that area, which may
// be larger than the request.
//
// A Transformer is returned to support image registration with other data.
func (m *Context) RenderWithTransformer() (image.Image, *Transformer, error) {
zoom, center, err := m.determineZoomCenter()
if err != nil {
return nil, nil, err
}
return m.renderWithZoomAndCenterAndTransformer(zoom, center)
}
func (m *Context) renderWithZoomAndCenterAndTransformer(zoom int, center s2.LatLng) (image.Image, *Transformer, error) {
m.result = RenderResult{
Zoom: zoom,
Center: center,
}
tileSize := m.tileProvider.TileSize
trans := newTransformer(m.width, m.height, zoom, center, tileSize)
img := image.NewRGBA(image.Rect(0, 0, trans.pWidth, trans.pHeight))
gc := gg.NewContextForRGBA(img)
if m.background != nil {
draw.Draw(img, img.Bounds(), &image.Uniform{m.background}, image.Point{}, draw.Src)
}
bounds := m.determineBounds()
leftX, _ := trans.LatLngToXY(bounds.Lo())
for _, object := range m.objects {
_, _, _, left := object.ExtraMarginPixels()
if leftX-left < 0 && zoom > 0 {
return m.renderWithZoomAndCenterAndTransformer(zoom-1, center)
}
}
// fetch and draw tiles to img
layers := []*TileProvider{m.tileProvider}
if m.overlays != nil {
layers = append(layers, m.overlays...)
}
for _, layer := range layers {
if err := m.renderLayer(gc, zoom, trans, tileSize, layer); err != nil {
return nil, nil, err
}
}
// draw map objects
for _, object := range m.objects {
object.Draw(gc, trans)
}
// draw attribution
if m.tileProvider.Attribution == "" {
return img, trans, nil
}
_, textHeight := gc.MeasureString(m.tileProvider.Attribution)
boxHeight := textHeight + 4.0
gc.SetRGBA(0.0, 0.0, 0.0, 0.5)
gc.DrawRectangle(0.0, float64(trans.pHeight)-boxHeight, float64(trans.pWidth), boxHeight)
gc.Fill()
gc.SetRGBA(1.0, 1.0, 1.0, 0.75)
gc.DrawString(m.tileProvider.Attribution, 4.0, float64(m.height)-4.0)
return img, trans, nil
}
// RenderWithBounds actually renders the map image including all map objects (markers, paths, areas).
// The returned image covers requested area as well as any tiles necessary to cover that area, which may
// be larger than the request.
//
// Specific bounding box of returned image is provided to support image registration with other data
func (m *Context) RenderWithBounds() (image.Image, s2.Rect, error) {
img, trans, err := m.RenderWithTransformer()
if err != nil {
return nil, s2.Rect{}, err
}
return img, trans.Rect(), nil
}
func (m *Context) renderLayer(gc *gg.Context, zoom int, trans *Transformer, tileSize int, provider *TileProvider) error {
t := NewTileFetcher(provider, m.cache)
if m.userAgent != "" {
t.SetUserAgent(m.userAgent)
}
tiles := (1 << uint(zoom))
for xx := 0; xx < trans.tCountX; xx++ {
x := trans.tOriginX + xx
if x < 0 {
x = x + tiles
} else if x >= tiles {
x = x - tiles
}
for yy := 0; yy < trans.tCountY; yy++ {
y := trans.tOriginY + yy
if y < 0 || y >= tiles {
log.Printf("Skipping out of bounds tile %d/%d", x, y)
continue
}
if tileImg, err := t.Fetch(zoom, x, y); err == nil {
gc.DrawImage(tileImg, xx*tileSize, yy*tileSize)
} else if err == errTileNotFound && provider.IgnoreNotFound {
log.Printf("Error downloading tile file: %s (Ignored)", err)
continue
} else {
log.Printf("Error downloading tile file: %s", err)
return err
}
}
}
return nil
}
func (m *Context) RenderResult() RenderResult {
return m.result
}