-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeocoder.go
More file actions
81 lines (75 loc) · 1.77 KB
/
geocoder.go
File metadata and controls
81 lines (75 loc) · 1.77 KB
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
// It will get coordinates for a given address.
package geocoder
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
// The expected reply from API (the bit we need).
type Reply struct {
Response struct {
GeoObjectCollection struct {
FeatureMember []struct {
GeoObject struct {
Point struct {
Pos string
}
}
}
}
}
}
// Coordinates.
type Coordinates struct {
Latitude float32
Longitude float32
}
// The url of Yandex Geocoder API.
const API_URL = "http://geocode-maps.yandex.ru/1.x/?format=json&results=1&geocode="
// Request calls Yandex Geocoder API.
func Request(address string) (Reply, error) {
url := API_URL + address
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
return Reply{}, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return Reply{}, err
}
var r Reply
err = json.Unmarshal(body, &r)
if err != nil {
return Reply{}, err
}
return r, nil
}
// AddressToCoordinates converts address to coordinates.
func AddressToCoordinates(address string) (Coordinates, error) {
r, err := Request(address)
if err != nil {
return Coordinates{}, err
}
if len(r.Response.GeoObjectCollection.FeatureMember) == 0 {
return Coordinates{}, errors.New("geocoder: the place hasn't been found: " + address)
}
pos := r.Response.GeoObjectCollection.FeatureMember[0].GeoObject.Point.Pos
points := strings.Split(pos, " ")
if len(points) < 2 {
return Coordinates{}, errors.New("geocoder: unexpected format of points (" + pos + ")")
}
lat, err := strconv.ParseFloat(points[1], 32)
if err != nil {
return Coordinates{}, err
}
lon, err := strconv.ParseFloat(points[0], 32)
if err != nil {
return Coordinates{}, err
}
c := Coordinates{float32(lat), float32(lon)}
return c, nil
}