-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeocoder.go
72 lines (64 loc) · 1.72 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
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"net/url"
)
const google_base_url string = "https://maps.googleapis.com/maps/api/geocode/json"
const NO_ADDRESS string = "No address provided"
const NO_RESULTS string = "No results returned"
type Geocoder struct {
apiKey string
}
type GeocodingResults struct {
Results []GeocodingResult `json:"results"`
}
type GeocodingResult struct {
Geometry GeocodingGeometry `json:"geometry"`
}
type GeocodingGeometry struct {
Location GeocodingLocation `json:"location"`
}
type GeocodingLocation struct {
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
}
func (g *Geocoder) GetLatLng(address string) (float64, float64, error) {
if len(address) > 0 {
req, err := url.Parse(google_base_url)
if err != nil {
log.Fatal("Could not generate request from base_url: %v", err)
}
values := req.Query()
values.Add("address", address)
values.Add("sensor", "false")
//values.Add("key", g.apiKey)
req.RawQuery = values.Encode()
log.Println("Making request for: " + req.String())
resp, err := http.Get(req.String())
if err != nil {
log.Printf("Could not make request: %v", err)
return -1, -1, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Could not read response: %v", err)
return -1, -1, err
}
var results GeocodingResults
err = json.Unmarshal(body, &results)
if err != nil {
log.Printf("Could not create GeocodingResults: %v", err)
return -1, -1, err
}
if len(results.Results) > 0 {
return results.Results[0].Geometry.Location.Lat, results.Results[0].Geometry.Location.Lng, nil
}
return -1, -1, errors.New(NO_RESULTS)
}
return -1, -1, errors.New(NO_ADDRESS)
}