-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmplace.go
96 lines (78 loc) · 2.33 KB
/
gmplace.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
package gmplace
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
)
// GoogleMapsPlaceBaseAPI base api of google maps place
const GoogleMapsPlaceBaseAPI = "https://maps.googleapis.com/maps/api/place"
// Prediction entity
type Prediction struct {
ID string `json:"id"`
Description string `json:"description"`
MatchedSubstrings []MatchedSubstring `json:"matched_substrings"`
PlaceID string `json:"place_id"`
Reference string `json:"reference"`
StructuredFormatting StructuredFormatting `json:"structured_formatting"`
Terms []Term `json:"terms"`
Types []string `json:"types"`
}
// MatchedSubstring entity
type MatchedSubstring struct {
Length int `json:"length"`
Offset int `json:"offset"`
}
// StructuredFormatting entity
type StructuredFormatting struct {
MainText string `json:"main_text"`
MainTextMatchedSubstrings []MatchedSubstring `json:"main_text_matched_substrings"`
SecondaryText string `json:"secondary_text"`
}
// Term entity
type Term struct {
Offset int `json:"offset"`
Value string `json:"value"`
}
// AutocompleteResult Google Maps Place Autocomplete results
type AutocompleteResult struct {
Predictions []Prediction `json:"predictions"`
Status string `json:"status"`
}
// GmPlace go package struct
type GmPlace struct {
key string
httpClient *http.Client
}
// Autocomplete Google Maps Place Autocomplete
// https://developers.google.com/places/web-service/autocomplete
func (p *GmPlace) Autocomplete(params map[string]string) (*AutocompleteResult, error) {
var result *AutocompleteResult
u, err := url.Parse(GoogleMapsPlaceBaseAPI)
if err != nil {
return nil, err
}
u.Path = path.Join(u.Path, "/autocomplete/json")
q := u.Query()
q.Set("key", p.key)
for key, value := range params {
q.Set(key, value)
}
u.RawQuery = q.Encode()
resp, err := p.httpClient.Get(u.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
buf, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(buf, &result)
return result, err
}
// New Google Maps Place
func New(key string) *GmPlace {
return &GmPlace{key, &http.Client{
Timeout: time.Second * 10,
}}
}