This repository has been archived by the owner on Aug 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
location_geocoding.go
200 lines (180 loc) · 5.05 KB
/
location_geocoding.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/paulmach/go.geojson"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
type GeoLocation struct {
Status string `json:"status"`
Results []GeocodingResult `json:"results"`
}
type GeocodingResult struct {
AddressComponents []GeocodingAddressComponent `json:"address_components"`
}
type GeocodingAddressComponent struct {
LongName string `json:"long_name"`
ShortName string `json:"short_name"`
Types []string `json:"types"`
}
/*
Extract a sane name from the geocoding object
*/
func (location *Location) Name() string {
unknownLocation := "Unknown"
var geoLocation GeoLocation
err := json.Unmarshal([]byte(location.Geocoding), &geoLocation)
if err != nil {
log.Printf("Error decoding location object: %v", err)
log.Printf("%v", location.Geocoding)
return "Unknown"
}
if geoLocation.Status != "OK" || len(geoLocation.Results) == 0 {
return unknownLocation
}
var postalTown, locality string
for _, addresscomponents := range geoLocation.Results[0].AddressComponents {
if stringSliceContains(addresscomponents.Types, "postal_town") {
postalTown = addresscomponents.LongName
}
if stringSliceContains(addresscomponents.Types, "locality") {
locality = addresscomponents.LongName
}
}
if postalTown != "" {
return postalTown
}
if locality != "" {
return locality
}
return unknownLocation
}
func GetGeocoding(place string) (*geojson.FeatureCollection, error) {
if configuration.GeocodeApiURL == "" {
err := errors.New("Geocoding API should not be blank")
InternalError(err)
return nil, err
}
if place == "" {
err := errors.New("Place should not be blank")
InternalError(err)
return nil, err
}
geocodingUrl := fmt.Sprintf(configuration.GeocodeApiURL, url.QueryEscape(place))
geocodingResponse, err := fetchGeocodingResponse(geocodingUrl)
if err != nil {
return nil, err
}
featureColletion, err := geojson.UnmarshalFeatureCollection([]byte(geocodingResponse))
if err != nil {
return nil, err
}
return featureColletion, nil
}
func (location *Location) GetReverseGeocoding() (string, error) {
if configuration.ReverseGeocodeApiURL == "" {
err := errors.New("Reverse Geocoding API should not be blank")
InternalError(err)
return "", err
}
geocodingUrl := fmt.Sprintf(configuration.ReverseGeocodeApiURL, location.Latitude, location.Longitude)
return fetchGeocodingResponse(geocodingUrl)
}
func fetchGeocodingResponse(geocodingUrl string) (string, error) {
defer timeTrack(time.Now())
response, err := http.Get(geocodingUrl)
if err != nil {
log.Printf("Error getting geolocation from API: %v", err)
return "", err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if response.StatusCode != 200 {
if err == nil {
body = []byte("")
}
err := errors.New(fmt.Sprintf("invalid response from Geolocation API: %v %v", response.StatusCode, body))
InternalError(err)
return "", err
}
if err != nil {
InternalError(err)
return "", err
}
return string(body), nil
}
func UpdateLatestLocationWithGeocoding(workChan <-chan bool) {
log.Print("Starting geocoding goroutine")
for {
_, more := <-workChan
if more {
log.Print("Updating latest geocoding")
var location Location
var id int
err := db.QueryRow("select id,ST_Y(ST_AsText(point)),ST_X(ST_AsText(point)) from locations order by devicetimestamp desc limit 1").Scan(&id, &location.Latitude, &location.Longitude)
if err != nil {
InternalError(err)
}
tx, err := db.Begin()
if err != nil {
InternalError(err)
}
geocoding, err := location.GetReverseGeocoding()
if err != nil {
InternalError(err)
} else {
_, err = tx.Exec("update locations set geocoding=$1 where id=$2", geocoding, id)
if err != nil {
log.Printf("Location that caused fail is: %s", geocoding)
tx.Rollback()
InternalError(err)
}
err = tx.Commit()
if err != nil {
InternalError(err)
} else {
log.Print("Geocoding complete")
}
}
} else {
log.Print("Got signal, quitting geocoding goroutine.")
return
}
}
}
func GeocodingCrawler(quitChan <-chan bool) {
log.Print("Starting geocoding backlog crawler")
ticker := time.NewTicker(10 * time.Second)
for {
select {
case <-ticker.C:
var location Location
var id int
err := db.QueryRow("select id,ST_Y(ST_AsText(point)),ST_X(ST_AsText(point)) from locations where geocoding is null and devicetimestamp<CURRENT_DATE - 1 order by devicetimestamp desc limit 1").Scan(&id, &location.Latitude, &location.Longitude)
if err != nil {
log.Print("Error fetching latest location without geocode")
break
}
geocoding, err := location.GetReverseGeocoding()
if err != nil {
log.Printf("Error reversing geocode for: %v", location)
break
} else {
_, err = db.Exec("update locations set geocoding=$1 where id=$2", geocoding, id)
if err != nil {
log.Printf("Location that caused fail is: %s", geocoding)
} else {
log.Printf("Geocoded location id=%v", id)
}
}
case <-quitChan:
log.Print("Clos")
return
}
}
}