-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
237 lines (205 loc) · 6.5 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
package main
import (
"encoding/json"
"log"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/dhconnelly/rtreego"
"github.com/paulsmith/gogeos/geos"
"github.com/voxelbrain/goptions"
)
// Holds the R-Tree used for searching data.
// The geographical objects stored in the R-Tree as described and searched
// through their bounding box. The goal of the R-Tree is only to quickly target
// which objects are near the point of interest.
var rt *rtreego.Rtree
var rt_countries *rtreego.Rtree
// Holds the translation between ISO-3166-2 country code and country details.
// This map can also be used to translate country names.
var countries_exp map[string]CountryDetails
// Interface to access the data embed in a rtreego.Spatial object
type SpatialData interface {
rtreego.Spatial
GetData() *GeoData
}
type GeoData struct {
Id int64 `json:"id"`
City string `json:"city,omitempty"`
CountryName string `json:"country"`
CountryCode_2 string `json:"country_iso3166-2"`
CountryCode_3 string `json:"country_iso3166-3"`
Type string `json:"type"`
Geom *geos.Geometry `json:"-"`
}
// Represents the data which will be stored in the R-Tree
type GeoObj struct {
bbox *rtreego.Rect
geoData *GeoData
}
// Function needed for storing data in the R-Tree
func (c *GeoObj) Bounds() *rtreego.Rect {
return c.bbox
}
// Function needed for accessing the data from the SpatialData interface
func (c *GeoObj) GetData() *GeoData {
return c.geoData
}
func suggestDownload(country_code2 string) {
if details, ok := countries_exp[country_code2]; ok {
log.Println("No city data found for", details.Name)
log.Println("Download here: http://download.gisgraphy.com/openstreetmap/csv/cities/" + country_code2 + ".tar.bz2")
}
}
// Parses /rg/<lat>/<lng> or /rg/<lat>/<lng>/<precision> and returns a JSON describing the reverse geocoding
func reverseGeocodingHandler(w http.ResponseWriter, r *http.Request) {
params := strings.Split(r.URL.Path[len("/rg/"):], "/")
if len(params) != 2 && len(params) != 3 {
http.Error(w, "Invalid format for lat/lon", http.StatusInternalServerError)
return
}
lat, err := strconv.ParseFloat(params[0], 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lng, err := strconv.ParseFloat(params[1], 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
precision := 1e-4
if len(params) == 3 {
precision, err = strconv.ParseFloat(params[2], 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
geodata, err := reverseGeocode(rt, lat, lng, precision)
if err == ErrNoMatchFound {
// Fallback to countries
geodata, err = reverseGeocode(rt_countries, lat, lng, precision)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
suggestDownload(geodata.CountryCode_2)
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if details, ok := countries_exp[geodata.CountryCode_2]; ok {
geodata.CountryName = details.Name
geodata.CountryCode_3 = details.ISO3166_3
}
b, err := json.Marshal(geodata)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
// Parses /gj/<south>/<west>/<north>/<east>.json and returns a GeoJSON containing the object currently loaded
func serveGeoJson(w http.ResponseWriter, r *http.Request) {
url := r.URL.Path[len("/gj/"):]
if strings.HasSuffix(url, ".json") {
url = url[:len(url)-len(".json")]
}
params := strings.Split(url, "/")
if len(params) != 4 {
http.Error(w, "Invalid format for bbox", http.StatusInternalServerError)
return
}
// String to float convertion
paramsf := make([]float64, 4)
for i, v := range params {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
paramsf[i] = f
}
bb, err := rtreego.NewRect(rtreego.Point{paramsf[1], paramsf[0]},
[]float64{paramsf[3] - paramsf[1], paramsf[2] - paramsf[0]})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// results := rt_countries.SearchIntersect(bb)
results := rt.SearchIntersect(bb)
gjc := gjFeatureCollection{
Type: "FeatureCollection",
Features: make([]gjFeature, len(results)),
}
for i, res := range results {
obj, _ := res.(SpatialData)
geod := obj.GetData()
gjf, err := ToGjFeature(geod.Geom)
if err != nil {
continue
}
gjc.Features[i] = gjf
gjc.Features[i].Properties = *geod
}
b, err := json.Marshal(gjc)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
// ---------------------------------------------------------------------------
func main() {
daddr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:8080")
if err != nil {
log.Fatal(err)
}
options := struct {
CityFiles []string `goptions:"-d, description='Data files to load'"`
CountryNames string `goptions:"-c, description='CSV file holding country names'"`
CountryShapes string `goptions:"-c, description='CSV file holding country shapes'"`
Help goptions.Help `goptions:"-h, --help, description='Show this help'"`
ListenAddr *net.TCPAddr `goptions:"-l, --listen, description='Listen address for HTTP server'"`
}{
CountryNames: "data/countries_en.csv",
CountryShapes: "data/countries.csv.bz2",
ListenAddr: daddr,
}
goptions.ParseAndFail(&options)
rt_countries = rtreego.NewTree(2, 10, 20)
_, err = load_freegeodb_countries_csv(rt_countries, options.CountryShapes)
if err != nil {
log.Fatal(err)
}
countries_exp, err = load_country_names(options.CountryNames)
if err != nil {
log.Fatal(err)
}
rt = rtreego.NewTree(2, 25, 50)
total_loaded_cities := 0
start_t := time.Now()
for _, fname := range options.CityFiles {
loaded, err := load_gisgraphy_cities_csv(rt, fname)
if err != nil {
log.Fatal(err)
}
total_loaded_cities += loaded
}
if total_loaded_cities > 0 {
log.Println("Loaded", total_loaded_cities, "cities in", time.Now().Sub(start_t))
}
log.Println("Starting HTTP server on", options.ListenAddr)
http.HandleFunc("/rg/", reverseGeocodingHandler)
http.HandleFunc("/gj/", serveGeoJson)
http.Handle("/", http.FileServer(http.Dir("html")))
err = http.ListenAndServe(options.ListenAddr.String(), nil)
if err != nil {
log.Fatal(err)
}
}