forked from WayneJz/teslamate-addr-fix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosm_client.go
72 lines (63 loc) · 1.63 KB
/
osm_client.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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
osmReverseURL = "https://nominatim.openstreetmap.org/reverse?lat=%.6f&lon=%.6f&format=json"
)
var cli *http.Client
func initProxyCli(proxy string, timeoutSec int) error {
timeout := time.Duration(timeoutSec) * time.Second
proxyfunc := http.ProxyFromEnvironment
if proxy != "" {
u, err := url.Parse(proxy)
if err != nil {
return err
}
proxyfunc = http.ProxyURL(u)
}
cli = &http.Client{
Transport: &http.Transport{
Proxy: proxyfunc,
},
Timeout: timeout,
}
return nil
}
type OsmRevAddress struct {
PlaceID int `json:"place_id"`
Licence string `json:"licence"`
OsmType string `json:"osm_type"`
OsmID int `json:"osm_id"`
Lat string `json:"lat"`
Lon string `json:"lon"`
DisplayName string `json:"display_name"`
Address map[string]interface{} `json:"address"`
Boundingbox []string `json:"boundingbox"`
}
func getAddressByProxy(latitude, longitude float64) (*OsmRevAddress, error) {
reqURL := fmt.Sprintf(osmReverseURL, latitude, longitude)
rsp, err := cli.Get(reqURL)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
if rsp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("osm returns error status, status=%d, url=%s", rsp.StatusCode, reqURL)
}
b, err := io.ReadAll(rsp.Body)
if err != nil {
return nil, err
}
address := &OsmRevAddress{}
err = json.Unmarshal(b, address)
if err != nil {
return nil, err
}
return address, nil
}