/
geocoder.go
98 lines (86 loc) · 2.27 KB
/
geocoder.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
// Package search is a geo-golang based HERE geocode/reverse geocode client for the Geocoding and Search API
package search
import (
"fmt"
"net/url"
"github.com/codingsince1985/geo-golang"
)
type (
baseURL struct{ forGeocode, forReverseGeocode string }
geocodeResponse struct {
Items []struct {
Address struct {
Label string
CountryCode string
CountryName string
StateCode string
State string
County string
District string
City string
Street string
PostalCode string
HouseNumber string
}
Position struct {
Lat float64
Lng float64
}
}
}
)
// Geocoder constructs HERE geocoder
func Geocoder(apiKey string, baseURLs ...string) geo.Geocoder {
p := "apiKey=" + url.QueryEscape(apiKey)
return geo.HTTPGeocoder{
EndpointBuilder: baseURL{
getGeocodeURL(p, baseURLs...),
getReverseGeocodeURL(p, baseURLs...)},
ResponseParserFactory: func() geo.ResponseParser { return &geocodeResponse{} },
}
}
func getGeocodeURL(p string, baseURLs ...string) string {
if len(baseURLs) > 0 {
return baseURLs[0]
}
return "https://geocode.search.hereapi.com/v1/geocode?" + p
}
func getReverseGeocodeURL(p string, baseURLs ...string) string {
if len(baseURLs) > 0 {
return baseURLs[0]
}
return "https://revgeocode.search.hereapi.com/v1/revgeocode?" + p
}
func (b baseURL) GeocodeURL(address string) string { return b.forGeocode + "&limit=1&q=" + address }
func (b baseURL) ReverseGeocodeURL(l geo.Location) string {
return b.forReverseGeocode + fmt.Sprintf("&limit=1&at=%f,%f", l.Lat, l.Lng)
}
func (r *geocodeResponse) Location() (*geo.Location, error) {
if len(r.Items) == 0 {
return nil, nil
}
p := r.Items[0].Position
return &geo.Location{
Lat: p.Lat,
Lng: p.Lng,
}, nil
}
func (r *geocodeResponse) Address() (*geo.Address, error) {
if len(r.Items) == 0 {
return nil, nil
}
res := r.Items[0].Address
addr := &geo.Address{
FormattedAddress: res.Label,
City: res.City,
Street: res.Street,
HouseNumber: res.HouseNumber,
Postcode: res.PostalCode,
State: res.State,
County: res.County,
Country: res.CountryName,
CountryCode: res.CountryCode,
Suburb: res.District,
}
return addr, nil
}