-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeocoding.go
More file actions
57 lines (47 loc) · 1.21 KB
/
geocoding.go
File metadata and controls
57 lines (47 loc) · 1.21 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
type Location struct {
Lat string `json:"lat"`
Lon string `json:"lon"`
DisplayName string `json:"display_name"`
}
func getCoordinates(city, country string) (float64, float64, string, error) {
query := fmt.Sprintf("%s, %s", city, country)
u, err := url.Parse("https://nominatim.openstreetmap.org/search")
if err != nil {
return 0, 0, "", err
}
q := u.Query()
q.Set("q", query)
q.Set("format", "json")
q.Set("limit", "1")
u.RawQuery = q.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return 0, 0, "", err
}
req.Header.Set("User-Agent", "CartoGo/1.0")
client := &http.Client{Timeout: 10 * time.Second}
resp, respErr := client.Do(req)
if respErr != nil {
return 0, 0, "", respErr
}
defer resp.Body.Close()
var locations []Location
if err := json.NewDecoder(resp.Body).Decode(&locations); err != nil {
return 0, 0, "", err
}
if len(locations) == 0 {
return 0, 0, "", fmt.Errorf("could not find coordinates for %s, %s", city, country)
}
var lat, lon float64
fmt.Sscanf(locations[0].Lat, "%f", &lat)
fmt.Sscanf(locations[0].Lon, "%f", &lon)
return lat, lon, locations[0].DisplayName, nil
}