/
util.go
71 lines (64 loc) · 1.4 KB
/
util.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
package slippy
import (
"errors"
"image"
"image/color"
_ "image/png"
"math"
"net/http"
)
// Earth Parameters
const (
MaxZ = 23
MinLat = -85.05112878
MaxLat = 85.05112878
MinLon = -180
MaxLon = 180
EarthRadiusM = 6378137
TileSize = 256
)
// clamp the value
func clamp(val, min, max float64) float64 {
if min > max {
panic("clamp: min cannot be greater than max")
}
return math.Min(math.Max(val, min), max)
}
// Gets the size of the x, y dimensions in pixels at the given zoom level
// x == y since the map is a square
func mapDimensions(zoom int) int {
return TileSize << uint(zoom)
}
var UserAgent = "Slippy/Go-Test"
func FetchImage(url string) (image.Image, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", UserAgent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotFound {
return BlankTile(), nil
}
return nil, errors.New(resp.Status)
}
img, _, err := image.Decode(resp.Body)
if err != nil {
return nil, err
}
return img, nil
}
func BlankTile() image.Image {
img := image.NewRGBA(image.Rect(0, 0, TileSize, TileSize))
for x := 0; x < TileSize; x++ {
for y := 0; y < TileSize; y++ {
img.Set(x, y, color.Black)
}
}
return img
}