-
Notifications
You must be signed in to change notification settings - Fork 20
/
geo.go
100 lines (80 loc) · 1.97 KB
/
geo.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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
)
const mapAPI = "https://nominatim.openstreetmap.org/search"
type geoLocation struct {
FormattedAddress string `json:"display_name"`
Lat string `json:"lat"`
Lng string `json:"lon"`
}
type geoResults []geoLocation
// Geocode is a geographic location
type Geocode struct {
Name string
Latitude float64
Longitude float64
}
// Locate returns the possible geocodes for a location
func Locate(location string) (l []Geocode, err error) {
dlog.Printf("Locating %s", location)
url := fmt.Sprintf("%s", mapAPI)
params := map[string]string{"q": location, "format": "json", "addressDetails": "1"}
var content []byte
if content, err = get(url, params); err != nil {
return
}
dlog.Printf("Gt results: %s", content)
var r geoResults
if err = json.Unmarshal(content, &r); err != nil {
return
}
for _, res := range r {
loc := &(res)
var gc Geocode
gc.Name = loc.FormattedAddress
gc.Latitude, _ = strconv.ParseFloat(loc.Lat, 64)
gc.Longitude, _ = strconv.ParseFloat(loc.Lng, 64)
l = append(l, gc)
}
return
}
// Location converts a Geocode to a Location
func (g *Geocode) Location() (l Location) {
l.Latitude = g.Latitude
l.Longitude = g.Longitude
l.Name = g.Name
l.ShortName = g.Name
return
}
func get(url string, params map[string]string) (data []byte, err error) {
var request *http.Request
if request, err = http.NewRequest("GET", url, nil); err != nil {
return
}
if params != nil {
values := request.URL.Query()
for k, v := range params {
values.Add(k, v)
}
request.URL.RawQuery = values.Encode()
}
dlog.Printf("request query: %s", request.URL.RawQuery)
var resp *http.Response
if resp, err = client.Do(request); err != nil {
return
}
defer resp.Body.Close()
data, err = io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
if data != nil {
dlog.Printf("Error getting data: %s", data)
}
err = fmt.Errorf(resp.Status)
}
return
}