forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geocode.go
73 lines (57 loc) · 1.39 KB
/
geocode.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
package geocode
/*
Geocode command for the Micro Bot
usage: geocode [address]
*/
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/micro/go-bot/command"
)
func init() {
command.Commands["^geocode "] = Geocode()
}
func Geocode() command.Command {
usage := "geocode [address]"
desc := "Returns the geocoded address; lat,lng"
type Location struct {
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
}
type Geometry struct {
Location Location `json:"location"`
}
type Result struct {
Geometry Geometry `json:"geometry"`
}
type Results struct {
Results []Result `json:"results"`
Status string `json:"status"`
}
return command.NewCommand("geocode", usage, desc, func(args ...string) ([]byte, error) {
if len(args) < 2 {
return []byte("geocode what?"), nil
}
u := url.Values{}
u.Set("address", strings.Join(args[1:], " "))
rsp, err := http.Get("https://maps.googleapis.com/maps/api/geocode/json?" + u.Encode())
if err != nil {
return nil, err
}
defer rsp.Body.Close()
var res Results
if err := json.NewDecoder(rsp.Body).Decode(&res); err != nil {
return nil, err
}
if res.Status != "OK" {
return nil, fmt.Errorf("returned status: %s", res.Status)
}
lat := res.Results[0].Geometry.Location.Lat
lng := res.Results[0].Geometry.Location.Lng
val := fmt.Sprintf("%.6f,%.6f", lat, lng)
return []byte(val), nil
})
}