gountries

package module
v0.0.0-...-bacd2f9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2021 License: MIT, MIT Imports: 13 Imported by: 0

README

gountries

wercker status codecov.io Go Report Card

Inspired by the countries gem for ruby.

Countries (ISO-3166-1), Country Subdivisions(ISO-3166-2), Currencies (ISO 4217), Geo Coordinates(ISO-6709) as well as translations, country borders and other stuff exposed as struct data.

All data is derived from the pariz/countries repo.

This is currently a work in progress, so things may change. More stuff will be added

Installation

go get github.com/pariz/gountries

Examples

Basic


import (
  "github.com/pariz/gountries"
  "fmt"
)


query := gountries.New()

/////////////////
// Find sweden //
/////////////////

sweden, _ := query.FindCountryByName("sweden")
// sweden, _ := query.FindCountryByAlpha("SE")
// sweden, _ := query.FindCountryByAlpha("SWE")

fmt.Println(sweden.Name.Common) // Output: Sweden
fmt.Println(sweden.Name.Official) // Output: Konungariket Sverige

fmt.Println(sweden.Translations["DEU"].Common) // Output: Schweden
fmt.Println(sweden.Translations["DEU"].Official) // Output: Königreich Schweden


A bit more advanced


import (
  "github.com/pariz/gountries"
  "fmt"
)

query := gountries.New()

////////////////////////////////////////////
// Find the bordering countries of Sweden //
////////////////////////////////////////////

sweden, _ := query.FindCountryByAlpha("SWE") // "SE" also works..

// Get the bordering countries of sweden
for _, country := range sweden.BorderingCountries() {
	fmt.Println(country.Name.Common)
}

// Output:
// Finland
// Norway

////////////////////////////////////
// Find all subdivisons for Sweden //
////////////////////////////////////

subdivisions := sweden.SubDivisions()

for _, subdivision := range subdivisions {
	fmt.Println(subdivision.Name)
}

// Output:
// Västerbottens län
// Uppsala län
// Södermanlands län
// Gotlands län
// Dalarnas län
// ...

//////////////////////////////////////////////////////////
// Find all countries bordering Germany and Switzerland //
//////////////////////////////////////////////////////////

countryQuery := Country{
	Borders: []string{
		"DEU",
		"CHE",
	},
}

countries := query.FindCountries(countryQuery)

for _, c := range countries {
	fmt.Println(c.Name.Common)
}

// Output:
// Austria
// France

///////////////////////////////////////////////////////////////////
// Calculate distance between Sweden and Germany (in Kilometers) //
///////////////////////////////////////////////////////////////////

se, _ := query.FindCountryByAlpha("SWE")
de, _ := query.FindCountryByAlpha("DEU")

distance := gountries.MeasureDistanceHaversine(se, de)
//distance := MeasureDistancePythagoras(se, de)

fmt.Println(distance)

// Output:
// 1430.1937864547901

distance = gountries.CalculateHaversine(
	se.Coordinates.MaxLatitude, se.Coordinates.MaxLongitude,
	de.Coordinates.MinLatitude, de.Coordinates.MinLongitude)

fmt.Println(distance)

// Output:
// 2641.26145088825


Using packed data

The data in the data/yaml subdirectory is embedded using go-bindata. Once you include this library in your project, you won't need to access the data directory. To add or update the data, make changes to the YAML files then run:

go-bindata -pkg gountries data/yaml/*

Testing

Has a pretty solid test coverage but is constantly improving.

Todo

  • Province/County querying (partially complete)
  • Measurement between coordinates
  • GeoJSON information
  • Suggestions?

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Asset

func Asset(name string) ([]byte, error)

Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetDigest

func AssetDigest(name string) ([sha256.Size]byte, error)

AssetDigest returns the digest of the file with the given name. It returns an error if the asset could not be found or the digest could not be loaded.

func AssetDir

func AssetDir(name string) ([]string, error)

AssetDir returns the file names below a certain directory embedded in the file by go-bindata. For example if you run go-bindata on data/... and data contains the following hierarchy:

data/
  foo.txt
  img/
    a.png
    b.png

then AssetDir("data") would return []string{"foo.txt", "img"}, AssetDir("data/img") would return []string{"a.png", "b.png"}, AssetDir("foo.txt") and AssetDir("notexist") would return an error, and AssetDir("") will return []string{"data"}.

func AssetInfo

func AssetInfo(name string) (os.FileInfo, error)

AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetNames

func AssetNames() []string

AssetNames returns the names of the assets.

func AssetString

func AssetString(name string) (string, error)

AssetString returns the asset contents as a string (instead of a []byte).

func CalculateHaversine

func CalculateHaversine(lat1, lon1, lat2, lon2 float64) (d float64)
Example
se, _ := query.FindCountryByAlpha("SWE")
de, _ := query.FindCountryByAlpha("DEU")

distance := MeasureDistanceHaversine(se, de)

fmt.Println(distance)

distance = CalculateHaversine(
	se.Coordinates.MaxLatitude, se.Coordinates.MaxLongitude,
	de.Coordinates.MinLatitude, de.Coordinates.MinLongitude)

fmt.Println(distance)
Output:

1430.1937864547901
2641.26145088825

func CalculatePythagorasEquirectangular

func CalculatePythagorasEquirectangular(lat1, lon1, lat2, lon2 float64) (d float64)
Example
se, _ := query.FindCountryByAlpha("SWE")
de, _ := query.FindCountryByAlpha("DEU")

distance := MeasureDistancePythagoras(se, de)

fmt.Println(distance)

distance = CalculatePythagorasEquirectangular(
	se.Coordinates.MaxLatitude, se.Coordinates.MaxLongitude,
	de.Coordinates.MinLatitude, de.Coordinates.MinLongitude)

fmt.Println(distance)
Output:

1430.5502701671583
2667.2283097795016

func Deg2Rad

func Deg2Rad(deg float64) float64

func Digests

func Digests() (map[string][sha256.Size]byte, error)

Digests returns a map of all known files and their checksums.

func MeasureDistanceHaversine

func MeasureDistanceHaversine(m1 Measurer, m2 Measurer) (distance float64)

MeasureDistanceHaversine measures distances betweeen two countries using Havesine equation

func MeasureDistancePythagoras

func MeasureDistancePythagoras(m1 Measurer, m2 Measurer) (distance float64)

MeasureDistancePythagoras measures distances betweeen two countries using Pythagoras equirect angular equation

func MustAsset

func MustAsset(name string) []byte

MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables.

func MustAssetString

func MustAssetString(name string) string

MustAssetString is like AssetString but panics when Asset would return an error. It simplifies safe initialization of global variables.

func RestoreAsset

func RestoreAsset(dir, name string) error

RestoreAsset restores an asset under the given directory.

func RestoreAssets

func RestoreAssets(dir, name string) error

RestoreAssets restores an asset under the given directory recursively.

Types

type BaseLang

type BaseLang struct {
	Common   string `json:"common"`
	Official string `json:"official"`
}

BaseLang is a basic structure for common language formatting in the JSON file

type Codes

type Codes struct {
	Alpha2 string `json:"cca2"`
	Alpha3 string `json:"cca3"`
	CIOC   string
	CCN3   string

	//CountryCode         string // Yaml
	CallingCodes []string `json:"callingCode"`

	InternationalPrefix string // Yaml
}

Codes contains various code representations

type Continent

type Continent struct {
	Name string
	Code string
}

type Continents

type Continents interface {
	FindContinent(continentName string) (Continent, error)
}

func NewContinents

func NewContinents() Continents

type Coordinates

type Coordinates struct {
	LongitudeString string `json:"longitude"`
	LatitudeString  string `json:"latitude"`

	MinLongitude float64
	MinLatitude  float64
	MaxLongitude float64
	MaxLatitude  float64
	Latitude     float64
	Longitude    float64
}

Coordinates contains the coordinates for both Country and SubDivision

type Country

type Country struct {
	Name struct {
		BaseLang `yaml:",inline"`
		Native   map[string]BaseLang
	} `json:"name"`

	EuMember    bool
	LandLocked  bool
	Nationality string

	TLDs []string `json:"tld"`

	Languages    map[string]string
	Translations map[string]BaseLang
	Currencies   []string `json:"currency"`
	Borders      []string

	// Grouped meta
	Codes
	Geo
	Coordinates
	// contains filtered or unexported fields
}

Country contains all countries and their country codes

func (*Country) BorderingCountries

func (c *Country) BorderingCountries() (countries []Country)

BorderingCountries returns the bordering countries the given Country

func (*Country) FindSubdivisionByCode

func (c *Country) FindSubdivisionByCode(code string) (result SubDivision, err error)

FindSubdivisionByCode fincs a country by given code

func (*Country) FindSubdivisionByName

func (c *Country) FindSubdivisionByName(name string) (result SubDivision, err error)

FindSubdivisionByName fincs a country by given name

func (Country) MeasurableCoordinates

func (c Country) MeasurableCoordinates() (lat, long float64)

MeasurableCoordinates provides long/lat for country struct it does not store a pointer receiver to Country, as it needs to implement the Measurer interface

func (*Country) SubDivisions

func (c *Country) SubDivisions() (subdivisions []SubDivision)

SubDivisions returns the subdivisions for the given Country

type Geo

type Geo struct {
	Region    string `json:"region"`
	SubRegion string `json:"subregion"`
	Continent string // Yaml
	Capital   string `json:"capital"`

	Area float64
}

Geo contains geographical information

type Measurer

type Measurer interface {
	MeasurableCoordinates() (lat, long float64)
}

Measurer provides coordinates for measurements

type Query

type Query struct {
	Countries          map[string]Country
	NameToAlpha2       map[string]string
	Alpha3ToAlpha2     map[string]string
	NativeNameToAlpha2 map[string]string

	SubDivisions map[string]SubDivision
}

Query contains queries for countries, cities, etc.

func New

func New() *Query

New creates an Query object and unmarshals the json file.

func NewFromPath

func NewFromPath(dataPath string) *Query

NewFromPath creates a Query object from data folder in provided path

func (*Query) FindAllCountries

func (q *Query) FindAllCountries() (countries map[string]Country)

FindAllCountries returns a list of all countries

func (Query) FindCountries

func (q Query) FindCountries(c Country) (countries []Country)

FindCountries finds a Country based on the given struct data

func (*Query) FindCountryByAlpha

func (q *Query) FindCountryByAlpha(code string) (result Country, err error)

FindCountryByAlpha fincs a country by given code

func (*Query) FindCountryByName

func (q *Query) FindCountryByName(name string) (result Country, err error)

FindCountryByName finds a country by given name

func (*Query) FindCountryByNativeName

func (q *Query) FindCountryByNativeName(name string) (result Country, err error)

FindCountryByNativeName

func (*Query) FindSubdivisionByName

func (q *Query) FindSubdivisionByName(subdivisionName string) (result SubDivision, err error)

FindSubdivisionByName find the subdivision given it's name

func (*Query) FindSubdivisionCountryByName

func (q *Query) FindSubdivisionCountryByName(subdivisionName string) (result Country, err error)

FindSubdivisionCountryByName finds the country of a given subdivision name

type SubDivision

type SubDivision struct {
	Name  string
	Names []string
	Code  string

	CountryAlpha2 string

	Coordinates
}

SubDivision contains Country subdivison information

func (*SubDivision) MeasurableCoordinates

func (sd *SubDivision) MeasurableCoordinates() (lat, long float64)

MeasurableCoordinates provides long/lat for country struct

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL