-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeocoding.go
More file actions
302 lines (265 loc) · 8.03 KB
/
geocoding.go
File metadata and controls
302 lines (265 loc) · 8.03 KB
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
package mastobots
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// YahooPlaceInfoResults は、Yahoo場所情報APIからのデータを格納する
type YahooPlaceInfoResults struct {
ResultSet struct {
Result []struct {
Name string `json:"Name"`
Where string `json:"Where"`
Combined string `json:"Combined"`
} `json:"Result"`
} `json:"ResultSet"`
}
// YahooContentsGeoCoderResults は、YahooコンテンツジオコーダAPIからのデータを格納する
type YahooContentsGeoCoderResults struct {
ResultInfo struct {
Count int `json:"Count"`
} `json:"ResultInfo"`
Feature []struct {
Name string `json:"Name"`
Geometry struct {
Coordinates string `json:"Coordinates"`
} `json:"Geometry"`
Property struct {
Address string `json:"Address"`
} `json:"Property"`
}
}
// SunInfo は、日の入りと日の出時刻を格納する
type SunInfo struct {
Results struct {
Rise string `json:"civil_twilight_begin"`
Set string `json:"civil_twilight_end"`
Noon string `json:"solar_noon"`
} `json:"results"`
}
// getLocDatafromCoordinates は、botの座標から所在地情報を取得して格納する
func getLocDataFromCoordinates(key string, lat, lng float64) (name, timeZone string, err error) {
key = url.QueryEscape(key)
query := "https://map.yahooapis.jp/placeinfo/V1/get?lat=" + fmt.Sprint(lat) + "&lon=" + fmt.Sprint(lng) + "&appid=" + key + "&sort=-score&output=json"
res, err := http.Get(query)
if err != nil {
log.Printf("info: map.yahooapis.jpへのリクエストに失敗しました:%s", err)
return
}
if code := res.StatusCode; code >= 400 {
err = fmt.Errorf("map.yahooapis.jpへの接続エラーです(%d)", code)
log.Printf("info: %s", err)
return
}
var yr YahooPlaceInfoResults
if err = json.NewDecoder(res.Body).Decode(&yr); err != nil {
log.Printf("info: map.yahooapis.jpからのレスポンスがデコードできませんでした:%s", err)
res.Body.Close()
return
}
res.Body.Close()
if yr.ResultSet.Result[0].Name == "" {
if yr.ResultSet.Result[0].Where == "" {
name = "地球のどこか"
} else {
name = yr.ResultSet.Result[0].Where
}
} else {
name = yr.ResultSet.Result[0].Where + "の" + yr.ResultSet.Result[0].Name
}
timeZone = f.GetTimezoneName(lng, lat)
return
}
// getLocDataFromString は、地名に該当する座標データを返す
func getLocDataFromString(key string, loc []string) (placeName string, lat, lng float64, err error) {
area := strings.Join(loc, "")
areaq := url.QueryEscape(area)
key = url.QueryEscape(key)
categories := [3]string{"address", "world", "landmark"}
for _, category := range categories {
query := ""
if category == "address" {
query = "https://map.yahooapis.jp/geocode/V1/geoCoder?appid=" + key + "&output=json&sort=address2&query=" + areaq
} else {
query = "https://map.yahooapis.jp/geocode/cont/V1/contentsGeoCoder?appid=" + key + "&category=" + category + "&output=json&query=" + areaq
}
res, errr := http.Get(query)
if errr != nil {
err = errr
log.Printf("info: Yahoo APIへのリクエストに失敗しました:%s", err)
return
}
if code := res.StatusCode; code >= 400 {
err = fmt.Errorf("yahoo APIへの接続エラーです(%d)", code)
log.Printf("info: %s", err)
return
}
var yc YahooContentsGeoCoderResults
if err = json.NewDecoder(res.Body).Decode(&yc); err != nil {
log.Printf("info: Yahoo APIからのレスポンスがデコードできませんでした:%s", err)
res.Body.Close()
return
}
res.Body.Close()
if yc.ResultInfo.Count > 0 {
if category == "address" {
placeName = yc.Feature[0].Name
} else {
placeName = yc.Feature[0].Property.Address + "の" + yc.Feature[0].Name
}
coorinates := strings.Split(yc.Feature[0].Geometry.Coordinates, ",")
lat, err = strconv.ParseFloat(coorinates[1], 64)
if err != nil {
log.Printf("info: 緯度データが不正です %s", err)
return
}
lng, err = strconv.ParseFloat(coorinates[0], 64)
if err != nil {
log.Printf("info: 経度データが不正です %s", err)
return
}
return
}
}
err = fmt.Errorf("そんな地名おまへんがな")
return
}
// getDayCycleBySunMovement は、太陽の出入り時刻と現在時刻に応じて寝起きの時刻を返す
func getDayCycleBySunMovement(zone string, lat, lng float64) (sleep, active time.Duration, cond string, err error) {
wt, st, err := getSleepWakeTimeBySunMovement(zone, lat, lng)
if err != nil {
return
}
if wt.IsZero() {
sleep = time.Until(st)
active = 0
cond = "極夜"
return
}
if st.IsZero() {
sleep = 0
active = time.Until(wt)
cond = "白夜"
return
}
sleep = time.Until(wt)
tillSleep := time.Until(st)
active = st.Sub(wt)
if active < 0 {
active += 24 * time.Hour
}
if active > tillSleep {
sleep = 0
active = tillSleep
}
return
}
// getSleepWakeTimeBySunMovement は、太陽の出入り時刻と現在時刻に応じて寝起きの時刻を返す
func getSleepWakeTimeBySunMovement(zone string, lat, lng float64) (wt, st time.Time, err error) {
var loc *time.Location
if strings.Contains(zone, "GMT") {
offset, _ := strconv.Atoi(strings.Replace(zone, "GMT", "", -1))
loc = time.FixedZone(zone, offset*60*60)
log.Printf("info: GMTからのオフセット:%d", offset)
} else {
loc, err = time.LoadLocation(zone)
}
if err != nil {
loc = time.Local
}
now := time.Now().In(loc)
today, tomorrow := "today", "tomorrow"
days := [...]string{today, tomorrow}
sunrise := make(map[string]time.Time, len(days))
sunset := make(map[string]time.Time, len(days))
noon := make(map[string]time.Time, len(days))
format := "2006-01-02T15:04:05-07:00"
for i, day := range days {
y, m, d := now.Add(time.Duration(i) * 24 * time.Hour).Date()
dst := fmt.Sprintf("%d-%d-%d", y, int(m), d)
url := "https://api.sunrise-sunset.org/json?" + "lat=" + fmt.Sprint(lat) + "&lng=" + fmt.Sprint(lng) + "&date=" + dst + "&formatted=0"
res, err := http.Get(url)
if err != nil {
log.Printf("info: 日の出日没時刻サイトへのリクエストに失敗しました:%s", err)
return wt, st, err
}
if code := res.StatusCode; code >= 400 {
err = fmt.Errorf("info 日の出日没時刻サイトへの接続エラーです(%d)", code)
log.Printf("info: %s", err)
return wt, st, err
}
var sun SunInfo
if err = json.NewDecoder(res.Body).Decode(&sun); err != nil {
log.Printf("info: %s の太陽の出入り時刻がデコードできませんでした:%s", day, err)
res.Body.Close()
return wt, st, err
}
res.Body.Close()
sunrise[day], _ = time.Parse(format, sun.Results.Rise)
sunset[day], _ = time.Parse(format, sun.Results.Set)
noon[day], _ = time.Parse(format, sun.Results.Noon)
}
for _, day := range days {
y, _, _ := sunrise[day].Date()
if y == 1970 {
wt, st = getExtremeCycle(noon, loc, lat)
return wt, st, nil
}
}
wt = sunrise[today]
st = sunset[today]
now = time.Now()
if sunrise[today].Before(now) {
wt = sunrise[tomorrow]
}
if sunset[today].Before(now) {
st = sunset[tomorrow]
}
return
}
// getExtremeCycle は、白夜あるいは極夜の生活サイクルを返す
func getExtremeCycle(noon map[string]time.Time, loc *time.Location, lat float64) (wt, st time.Time) {
now := time.Now()
today, tomorrow := "today", "tomorrow"
isWhite := whiteOrBlack(loc, lat)
if isWhite {
// wtを1日で最も暗い時刻に設定
wt = noon[today].Add(12 * time.Hour)
if wt.Before(now) {
wt = noon[tomorrow].Add(12 * time.Hour)
}
st = time.Time{}
} else {
// stを1日で最も明るい時刻に設定
wt = time.Time{}
st = noon[today]
if st.Before(now) {
st = noon[tomorrow]
}
}
return
}
// whiteOrBlack は、現在その地点が白夜か極夜かを返す
func whiteOrBlack(loc *time.Location, lat float64) bool {
now := time.Now().In(loc)
_, m, _ := now.Date()
if lat > 0 {
if 3 < int(m) && int(m) < 10 {
// 白夜
return true
}
// 極夜
return false
}
if 3 < int(m) && int(m) < 10 {
// 極夜
return false
}
// 白夜
return true
}