area.go
1.9 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package area
import (
_ "embed"
"encoding/json"
)
type ProvinceCity struct {
Provinces []*Province
Cities []*City
ProvincesCity map[string][]*City
}
func (p *ProvinceCity) LoadProvincesCity(provinces []*Province, cities []*City) {
p.Provinces = provinces
p.Cities = cities
for i := range provinces {
p.ProvincesCity[provinces[i].Province] = make([]*City, 0)
}
for i := range cities {
if _, ok := p.ProvincesCity[cities[i].Province]; ok {
p.ProvincesCity[cities[i].Province] = append(p.ProvincesCity[cities[i].Province], cities[i])
}
}
}
var DefaultProvinceCity *ProvinceCity
// data source :https://github.com/uiwjs/province-city-china/tree/gh-pages
//go:embed city.json
var city []byte
//go:embed province.json
var province []byte
func SetUp() {
DefaultProvinceCity = &ProvinceCity{
Provinces: make([]*Province, 0),
Cities: make([]*City, 0),
ProvincesCity: make(map[string][]*City),
}
var cities []*City = make([]*City, 0)
var provinces []*Province = make([]*Province, 0)
err := json.Unmarshal(city, &cities)
if err != nil {
panic(err)
}
err = json.Unmarshal(province, &provinces)
if err != nil {
panic(err)
}
DefaultProvinceCity.LoadProvincesCity(provinces, cities)
}
/*
eg:
{
"code": "130100",
"name": "石家庄市",
"province": "13",
"city": "01"
}
*/
type City struct {
Code string `json:"code"`
Name string `json:"name"`
Province string `json:"province"`
City string `json:"city"`
}
/*
eg:
{
"code": "110000",
"name": "北京市",
"province": "11"
}
*/
type Province struct {
Code string `json:"code"`
Name string `json:"name"`
Province string `json:"province"`
}
func Provinces() []*Province {
return DefaultProvinceCity.Provinces
}
func Cities() []*City {
return DefaultProvinceCity.Cities
}
func ProvinceCities(provinceCode string) []*City {
if v, ok := DefaultProvinceCity.ProvincesCity[provinceCode]; ok {
return v
}
return []*City{}
}