yageocoding.GetData   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nop 2
dl 0
loc 15
rs 9.9
c 0
b 0
f 0
1
package yageocoding
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"fmt"
7
	"net/http"
8
	"strings"
9
)
10
11
// YaGeoResponse contains response data
12
type YaGeoResponse struct {
13
	Response struct {
14
		ObjectCollection YaGeoObjectCollection `json:"GeoObjectCollection"`
15
	} `json:"response"`
16
}
17
18
// YaGeoObjectCollection contains geo objects
19
type YaGeoObjectCollection struct {
20
	MetaData YaGeoMetaData `json:"metaDataProperty"`
21
	Member   []YaGeoMember `json:"featureMember"`
22
}
23
24
// YaGeoMetaData contains metadata
25
type YaGeoMetaData struct {
26
	ResponseMetaData struct {
27
		Request string `json:"request"`
28
		Found   string `json:"found"`
29
		Results string `json:"results"`
30
	} `json:"GeocoderResponseMetaData"`
31
}
32
33
// YaGeoMember contains object data
34
type YaGeoMember struct {
35
	GeoObject struct {
36
		MetaData    YaGeoMemberMetaData `json:"metaDataProperty"`
37
		Description string              `json:"description"`
38
		Name        string              `json:"name"`
39
		Point       struct {
40
			Pos string `json:"pos"`
41
		} `json:"Point"`
42
	} `json:"GeoObject"`
43
}
44
45
// YaGeoMemberMetaData contains member metadata
46
type YaGeoMemberMetaData struct {
47
	Meta struct {
48
		Kind      string `json:"kind"`
49
		Text      string `json:"text"`
50
		Precision string `json:"precision"`
51
	} `json:"GeocoderMetaData"`
52
}
53
54
// YaGeoAddress contains address structure
55
type YaGeoAddress struct {
56
	CountryCode string                  `json:"country_code"`
57
	PostalCode  string                  `json:"postal_code"`
58
	Formatted   string                  `json:"formatted"`
59
	Components  []YaGeoAddressComponent `json:"Components"`
60
}
61
62
// YaGeoAddressComponent is address component
63
type YaGeoAddressComponent struct {
64
	Kind string `json:"kind"`
65
	Name string `json:"name"`
66
}
67
68
// GetCoordinates returns coordinates
69
func (loc *YaGeoResponse) GetCoordinates() (string, string) {
70
	if len(loc.Response.ObjectCollection.Member) == 0 {
71
		return "0", "0"
72
	}
73
74
	str := strings.Split(loc.Response.ObjectCollection.Member[0].GeoObject.Point.Pos, " ")
75
	return str[0], str[1]
76
}
77
78
// GetData creates request to API and returns result
79
func GetData(key, location string) (result YaGeoResponse, err error) {
80
	resp, err := http.Get(fmt.Sprintf("https://geocode-maps.yandex.ru/1.x/?format=json&geocode=%v&apikey=%v", location, key))
81
	if err != nil {
82
		return
83
	}
84
85
	err = json.NewDecoder(resp.Body).Decode(&result)
86
	if err != nil {
87
		return result, err
88
	}
89
90
	if len(result.Response.ObjectCollection.Member) == 0 {
91
		return result, errors.New("location not fount")
92
	}
93
	return
94
}
95