-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
249 lines (228 loc) · 5.99 KB
/
main.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
package main
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/gorilla/mux"
"github.com/hashicorp/golang-lru"
"gopkg.in/redis.v3"
"io/ioutil"
"math"
"net/http"
"os"
"runtime"
"strconv"
)
var (
imageCache *lru.Cache
mapCache *redis.Client
)
const (
prefix string = "map"
imageCacheLen int = 2000
minZoom uint = 9
imageLength int = 360
degreeToSecond = 3600
listenAddress string = ":8000"
)
type Point struct {
lon, lat float64
serialLon, serialLat int //latitude and longitude for map file
subSerialX, subSerialY int //0.1*0.1 degree image location in 1*1 degree area
pixelX, pixelY int //pixel in one image
imageUUID int // image UUID of the point
}
func (p *Point) genMapInfo() {
p.serialLon = int(p.lon)
p.serialLat = int(p.lat)
p.imageUUID = 0
if p.lon <= 0 {
p.serialLon = -p.serialLon
p.serialLon++
p.imageUUID |= 1 << 0
}
if p.lat < 0 {
p.serialLat = -p.serialLat
p.serialLat++
p.imageUUID |= 1<<1
}
pixelInOneDegreeX := ((int)((p.lon-math.Floor(p.lon))*degreeToSecond) + degreeToSecond) % degreeToSecond
pixelInOneDegreeY := (degreeToSecond - (int)((p.lat-math.Floor(p.lat))*degreeToSecond)) % degreeToSecond
p.subSerialX = pixelInOneDegreeX / imageLength
p.subSerialY = pixelInOneDegreeY / imageLength
p.pixelX = pixelInOneDegreeX % imageLength
p.pixelY = pixelInOneDegreeY % imageLength
p.imageUUID = p.serialLon | (p.imageUUID << 8)
p.imageUUID = p.serialLat | (p.imageUUID << 8)
p.imageUUID = p.subSerialX | (p.imageUUID << 4)
p.imageUUID = p.subSerialY | (p.imageUUID << 4)
}
func newPoint(lon, lat float64) *Point {
p := new(Point)
p.lon = lon
p.lat = lat
p.genMapInfo()
return p
}
func init() {
var err error
runtime.GOMAXPROCS(runtime.NumCPU())
imageCache, err = lru.New(imageCacheLen)
if err != nil {
fmt.Println(err)
}
mapCache = redis.NewClient(&redis.Options{
Addr: "redis:6379",
})
mapCache.ConfigSet("save", "60 10")
}
func XYToLonLat(xtile, ytile int, zoom uint) *Point {
var lon_deg, lat_deg float64
b := (1 << zoom)
n := float64(b)
lon_deg = (float64)(xtile*360)/n - 180
lat_deg = math.Atan(math.Sinh(math.Pi*(1-2*(float64)(ytile)/n))) * 180 / math.Pi
return newPoint(lon_deg, lat_deg)
}
func lnglatToXY(p *Point, zoom int) (int, int) {
lat_rad := p.lat * math.Pi / 180
n := 1 << (uint)(zoom)
xtile := (int)(math.Floor((p.lon + 180) / 360 * (float64)(n)))
ytile := (int)((1 - math.Log(math.Tan(lat_rad)+1/math.Cos(lat_rad))/math.Pi) * (float64)(n) / 2)
return xtile, ytile
}
func getImageFileName(p *Point) string {
var (
lat_dir, lon_dir string
)
if p.lat > 0 {
lat_dir = "N"
} else {
lat_dir = "S"
}
if p.lon >= 0 {
lon_dir = "E"
} else {
lon_dir = "W"
}
return fmt.Sprintf("%s/%s%02d/%s%03d/%1d%1d", prefix, lat_dir, p.serialLat, lon_dir, p.serialLon, p.subSerialX, p.subSerialY)
}
func getImage(p *Point) *[imageLength][imageLength]int16 {
var img *[imageLength][imageLength]int16
imgInterface, cached := imageCache.Get(p.imageUUID)
if cached {
img = imgInterface.(*[imageLength][imageLength]int16)
} else {
file, err := os.Open(getImageFileName(p))
if err != nil {
return nil
}
defer file.Close()
fileByte, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
return nil
}
fileBuffer := bytes.NewReader(fileByte)
img = new([imageLength][imageLength]int16)
for i := 0; i < imageLength; i++ {
for j := 0; j < imageLength; j++ {
err := binary.Read(fileBuffer, binary.LittleEndian, &img[i][j])
if err != nil {
fmt.Println(err)
return nil
}
}
}
imageCache.Add(p.imageUUID, img)
}
return img
}
func getMap(i0, j0 int, zoom uint, size_index int) []byte {
var (
latSpan, lonSpan float64
w bytes.Buffer
img *[imageLength][imageLength]int16
)
pStart := XYToLonLat(i0, j0, zoom)
pEnd := XYToLonLat(i0+1, j0+1, zoom)
fmt.Printf("%f\t%f\t%f\t%f\n", pStart.lat, pStart.lon, pEnd.lat, pEnd.lon)
size := 1 << (uint)(size_index)
latSpan = (pEnd.lat - pStart.lat) / (float64)(size)
lonSpan = (pEnd.lon - pStart.lon) / (float64)(size)
if zoom < minZoom {
for i := 0; i <= size; i++ {
for j := 0; j <= size; j++ {
binary.Write(&w, binary.LittleEndian, int16(0))
}
}
} else {
for i := 0; i <= size; i++ {
var p Point
p.lat = pEnd.lat - (float64)(i)*latSpan
for j := 0; j <= size; j++ {
p.lon = pStart.lon + (float64)(j)*lonSpan
p.genMapInfo()
img = getImage(&p)
if img == nil {
binary.Write(&w, binary.LittleEndian, int16(0))
continue
}
binary.Write(&w, binary.LittleEndian, img[p.pixelX][p.pixelY])
}
}
}
return w.Bytes()
}
func mapHandler(w http.ResponseWriter, r *http.Request) {
var (
i0, j0, size_index, zoomi int
zoom uint
err error
response []byte
)
para := mux.Vars(r)
if i0, err = strconv.Atoi(para["i"]); err != nil {
return
}
if j0, err = strconv.Atoi(para["j"]); err != nil {
return
}
if zoomi, err = strconv.Atoi(para["zoom"]); err != nil {
return
}
zoom = uint(zoomi)
if size_index, err = strconv.Atoi(para["size"]); err != nil {
return
}
fmt.Printf("%s\n", r.URL)
responseCache := mapCache.Get(r.URL.String())
if responseCache.Err() == redis.Nil { // not cached
response = getMap(i0, j0, zoom, size_index)
mapCache.Set(r.URL.String(), response, 0)
} else if responseCache.Err() != nil { // redis error or not connected
response = getMap(i0, j0, zoom, size_index)
fmt.Println(responseCache.Err())
} else { // cached
response, err = responseCache.Bytes()
}
// write response
if len(response) == 0 {
w.WriteHeader(http.StatusNoContent)
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Println(err)
} else {
w.WriteHeader(http.StatusOK)
w.Write(response)
}
}
func main() {
route := mux.NewRouter()
route.HandleFunc("/{i:[0-9]+}/{j:[0-9]+}/{zoom:[0-9]+}/{size:[0-9]+}", mapHandler).Methods("GET")
http.Handle("/", route)
err := http.ListenAndServe(listenAddress, nil)
if err != nil {
fmt.Println(err)
}
}