geocodio

package module
v0.0.0-...-927308f Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2021 License: MIT Imports: 11 Imported by: 0

README

geocodio

GoDoc Go Report Card Coverage

Go client for Geocodio API v1

Usage

Geocode
import(
  "github.com/stevepartridge/geocodio"
  "fmt"
)

func main() {
	gc, err := geocodio.New("YOUR_API_KEY")
	// or if env var GEOCODIO_API_KEY is set
	// gc, err := geocodio.New()
	if err != nil {
		panic(err)
	}
	result, err := gc.Geocode("42370 Bob Hope Dr, Rancho Mirage, CA")
	if err != nil {
		panic(err)
	}
	fmt.Printf("Geocode Result %v", result)
}
Reverse Geocode
import(
  "github.com/stevepartridge/geocodio"
  "fmt"
)

func main() {
	gc, err := geocodio.NewGeocodio("YOUR_API_KEY")
	// or if env var GEOCODIO_API_KEY is set
	// gc, err := geocodio.New()
	if err != nil {
		panic(err)
	}
	result, err := gc.ReverseGeocode(38.9002898, -76.9990361)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Reverse Geocode Result %v", result)
}

Tests

You can run the tests leveraging your API key as an enviroment variable from terminal (*nix).

API_KEY=<YOUR_API_KEY> go test -v -cover

Documentation

Index

Constants

View Source
const (
	// MethodGet constant
	MethodGet = "GET"
	// MethodPost constant
	MethodPost = "POST"
)
View Source
const (
	EnvGeocodioAPIKey = "GEOCODIO_API_KEY"
	EnvOldAPIKey      = "API_KEY"
)
View Source
const (
	// GeocodioAPIBaseURLv1 is the Geocod.io Base URL
	GeocodioAPIBaseURLv1 = "https://api.geocod.io/v1.6"
)

Variables

View Source
var (
	// ErrReverseGecodeMissingLatLng error when a lat/lng is not provided
	ErrReverseGecodeMissingLatLng = errors.New("Latitude and longitude must not be empty")
	// ErrMissingAPIKey error
	ErrMissingAPIKey = errors.New("Missing or empty API key")
	// ErrAddressIsEmpty error
	ErrAddressIsEmpty = errors.New("Address must not be empty")
	// ErrBatchAddressesIsEmpty error
	ErrBatchAddressesIsEmpty = errors.New("At least one address is required for batch query")
	// ErrReverseBatchMissingCoords error
	ErrReverseBatchMissingCoords = errors.New("Missing minimum coordinates")
	// ErrReverseBatchInvalidCoordsPairs error
	ErrReverseBatchInvalidCoordsPairs = errors.New("Invalid list of coordinate pairs")
	// ErrNoResultsFound
	ErrNoResultsFound = errors.New("No results found")
)

Functions

This section is empty.

Types

type Address

type Address struct {
	Query        string     `json:"query"`
	Components   Components `json:"address_components"`
	Formatted    string     `json:"formatted_address"`
	Location     Location   `json:"location"`
	Accuracy     float64    `json:"accuracy"`
	AccuracyType string     `json:"accuracy_type"`
	Source       string     `json:"source"`
	Fields       Fields     `json:"fields,omitempty"`
}

type BatchResponse

type BatchResponse struct {
	Results []BatchResult `json:"results"`
	Debug   struct {
		RawResponse  []byte `json:"-"`
		RequestedURL string `json:"requested_url"`
		Status       string `json:"status"`
		StatusCode   int    `json:"status_code"`
	} `json:"-"`
}

BatchResponse

func (*BatchResponse) ResponseAsString

func (self *BatchResponse) ResponseAsString() string

ResponseAsString helper to return raw response

func (*BatchResponse) SaveDebug

func (self *BatchResponse) SaveDebug(requestedURL, status string, statusCode int, body []byte)

type BatchResult

type BatchResult struct {
	Query    string          `json:"query"`
	Response BatchResultItem `json:"response"`
}

BatchResult

type BatchResultItem

type BatchResultItem struct {
	Input   Input     `json:"input,omitempty"`
	Results []Address `json:"results"`
	Error   string    `json:"error,omitempty"`
}

type Bio

type Bio struct {
	LastName  string `json:"last_name"`
	FirstName string `json:"first_name"`
	Birthday  string `json:"birthday"`
	Gender    string `json:"gender"`
	Party     string `json:"party"`
}

Bio field

"bio": {
	"last_name": "Beyer",
	"first_name": "Donald",
	"birthday": "1950-06-20",
	"gender": "M",
	"party": "Democrat"
}

type CarrierRoute

type CarrierRoute struct {
	ID          string `json:"id"`
	Description string `json:"description"`
}

type Census

type Census struct {
	Year                      int             `json:"census_year"`
	StateFIPS                 string          `json:"state_fips"`
	CountyFIPS                string          `json:"county_fips"`
	TractCode                 string          `json:"tract_code"`
	BlockCode                 string          `json:"block_code"`
	BlockGroup                string          `json:"block_group"`
	FullFIPS                  string          `json:"full_fips"`
	Place                     Place           `json:"place"`
	MetroMicroStatisticalArea StatisticalArea `json:"metro_micro_statistical_area"`
	CombinedStatisticalArea   StatisticalArea `json:"combined_statistical_area"`
	MetropolitanDivision      StatisticalArea `json:"metropolitan_division"`
	Source                    string          `json:"source"`
}

Census field

{
	"census_year": 2010,
	"state_fips": "51",
	"county_fips": "51013",
	"tract_code": "101801",
	"block_code": "1004",
	"block_group": "1",
	"full_fips": "510131018011004",
	"place": {
		"name": "Arlington",
		"fips": "5103000"
	},
	"metro_micro_statistical_area": {
		"name": "Washington-Arlington-Alexandria, DC-VA-MD-WV",
		"area_code": "47900",
		"type": "metropolitan"
	},
	"combined_statistical_area": {
		"name": "Washington-Baltimore-Northern Virginia, DC-MD-VA-WV",
		"area_code": "51548"
	},
	"metropolitan_division": {
		"name": "Washington-Arlington-Alexandria, DC-VA-MD-WV",
		"area_code": "47894"
	},
	"source": "US Census Bureau"
}

type CensusACS

type CensusACS struct {
	Meta         CensusMeta   `json:"meta"`
	Demographics *Demographic `json:"demographics,omitempty"`
	Economics    *Economics   `json:"economics,omitempty"`
	Families     *Families    `json:"families,omitempty"`
	Housing      *Housing     `json:"housing,omitempty"`
	Social       *Social      `json:"social,omitempty"`
}

type CensusDataPoint

type CensusDataPoint struct {
	Value         float64          `json:"value,omitempty"`
	MarginOfError float64          `json:"margin_of_error,omitempty"`
	Percentage    float64          `json:"percentage,omitempty"`
	TableID       string           `json:"table_id,omitempty"`
	Universe      string           `json:"universe,omitempty"`
	Total         *CensusDataPoint `json:"Total,omitempty"`
}

type CensusMeta

type CensusMeta struct {
	Source              string `json:"source,omitempty"`
	SurveyYears         string `json:"survey_years,omitempty"`
	SurveyDurationYears string `json:"survey_duration_years,omitempty"`
	TableID             string `json:"table_id,omitempty"`
	Universe            string `json:"universe,omitempty"`
}

type CensusResults

type CensusResults struct {
	Census2010 *Census `json:"2010,omitempty"`
	Census2011 *Census `json:"2011,omitempty"`
	Census2012 *Census `json:"2012,omitempty"`
	Census2013 *Census `json:"2013,omitempty"`
	Census2014 *Census `json:"2014,omitempty"`
	Census2015 *Census `json:"2015,omitempty"`
	Census2016 *Census `json:"2016,omitempty"`
	Census2017 *Census `json:"2017,omitempty"`
	Census2018 *Census `json:"2018,omitempty"`
	Census2019 *Census `json:"2019,omitempty"`
	Census2020 *Census `json:"2020,omitempty"`
}

type Components

type Components struct {
	Number          string `json:"number"`
	Street          string `json:"street"`
	Suffix          string `json:"suffix"`
	SecondaryNumber string `json:"secondarynumber"`
	SecondaryUnit   string `json:"secondaryunit"`
	PostDirectional string `json:"postdirectional"`
	FormattedStreet string `json:"formatted_street"`
	City            string `json:"city"`
	State           string `json:"state"`
	Zip             string `json:"zip"`
	County          string `json:"county"`
	Country         string `json:"country"`
	PreDirectional  string `json:"predirectional"`
	Prefix          string `json:"prefix"`
}

Components

"address_components": {
	"number": "1109",
	"predirectional": "N",
	"street": "Highland",
	"suffix": "St",
	"formatted_street": "N Highland St",
	"city": "Arlington",
	"county": "Arlington County",
	"state": "VA",
	"zip": "22201",
	"country": "US"
},

type CongressionalDistrict

type CongressionalDistrict struct {
	Name               string       `json:"name"`
	DistrictNumber     int          `json:"district_number"`
	CongressNumber     string       `json:"congress_number"`
	CongressYears      string       `json:"congress_years"`
	Proportion         int          `json:"congress_years"`
	CurrentLegislators []Legislator `json:"current_legislators"` // v1.2+
}

Congressional District field

"name": "Congressional District 8", "district_number": 8, "congress_number": "116th", "congress_years": "2019-2021", "proportion": 1, "current_legislators": [...]

type CongressionalSocial

type CongressionalSocial struct {
	RSSURL    string `json:"rss_url"`
	Twitter   string `json:"twitter"`
	Facebook  string `json:"facebook"`
	YouTube   string `json:"youtube"`
	YouTubeID string `json:"youtube_id"`
}

Social field

"social": {
	"rss_url": null,
	"twitter": "RepDonBeyer",
	"facebook": "RepDonBeyer",
	"youtube": null,
	"youtube_id": "UCPJGVbOVcAVGiBwq8qr_T9w"
}

type Contact

type Contact struct {
	URL         string `json:"url"`
	Address     string `json:"address"`
	Phone       string `json:"phone"`
	ContactForm string `json:"contact_form"`
}

Contact field

"contact": {
	"url": "https://beyer.house.gov",
	"address": "1119 Longworth House Office Building Washington DC 20515-4608",
	"phone": "(202) 225-4376",
	"contact_form": null
}

type Demographic

type Demographic struct {
	MedianAge            map[string]CensusDataPoint `json:"Median age"`
	PopulationByAgeRange map[string]CensusDataPoint `json:"Population by age range"`
	Sex                  map[string]CensusDataPoint `json:"Sex"`
	RaceAndEthnicity     map[string]CensusDataPoint `json:"Race and ethnicity"`
}

type Economics

type Economics struct {
	NumberOfHouseholds    NumberOfHouseholds    `json:"Number of households"`
	MedianHouseholdIncome MedianHouseholdIncome `json:"Median household income"`
	HouseholdIncome       HouseholdIncome       `json:"Household income"`
}

type ErrorResponse

type ErrorResponse struct {
	Message string    `json:"error"`
	Results []Address `json:"results"`
}

type FacilityCode

type FacilityCode struct {
	Code        string `json:"code"`
	Description string `json:"description"`
}

type Families

type Families struct {
	HouseholdTypeByHousehold  map[string]CensusDataPoint `json:"Household type by household"`
	HouseholdTypeByPopulation map[string]CensusDataPoint `json:"Household type by population"`
	MaritalStatus             map[string]CensusDataPoint `json:"Marital status"`
}

type Fields

type Fields struct {
	Timezone                  Timezone                  `json:"timezone,omitempty"`
	Zip4                      Zip4                      `json:"zip4,omitempty"`
	CongressionalDistrict     CongressionalDistrict     `json:"congressional_district,omitempty"`  // v1.0
	CongressionalDistricts    []CongressionalDistrict   `json:"congressional_districts,omitempty"` // v1.1+
	StateLegislativeDistricts StateLegislativeDistricts `json:"state_legislative_districts,omitempty"`
	SchoolDistricts           SchoolDistricts           `json:"school_districts,omitempty"`
	Census                    CensusResults             `json:"census,omitempty"`
	ACS                       CensusACS                 `json:"acs,omitempty"`
}

Fields

type GeocodeResult

type GeocodeResult struct {
	Input   Input    `json:"input,omitempty"`
	Results []Result `json:"results"`
	Debug   struct {
		RawResponse  []byte `json:"-"`
		RequestedURL string `json:"requested_url"`
		Status       string `json:"status"`
		StatusCode   int    `json:"status_code"`
	} `json:"-"`
}

GeocodeResponse

func (*GeocodeResult) Error

func (self *GeocodeResult) Error() string

func (*GeocodeResult) ResponseAsString

func (self *GeocodeResult) ResponseAsString() string

ResponseAsString helper to return raw response

func (*GeocodeResult) SaveDebug

func (self *GeocodeResult) SaveDebug(requestedURL, status string, statusCode int, body []byte)

type Geocodio

type Geocodio struct {
	APIKey string
}

Geocodio is the base struct

func New

func New(apiKey ...string) (*Geocodio, error)

New creates a Geocodio instance based on an API key in either the environment or passed in as the first string value

func NewGeocodio

func NewGeocodio(apiKey string) (*Geocodio, error)

NewGeocodio is a helper to create new Geocodio reference since 1.6+ this is kept for backwards compatiblity this is deprecatd and will be removed in 2+

func (*Geocodio) Geocode

func (g *Geocodio) Geocode(address string) (GeocodeResult, error)

Geocode single address See: http://geocod.io/docs/#toc_4

func (*Geocodio) GeocodeAndReturnCongressionalDistrict

func (g *Geocodio) GeocodeAndReturnCongressionalDistrict(address string) (GeocodeResult, error)

GeocodeAndReturnCongressionalDistrict will geocode and include Congressional District in the fields response

func (*Geocodio) GeocodeAndReturnStateLegislativeDistricts

func (g *Geocodio) GeocodeAndReturnStateLegislativeDistricts(address string) (GeocodeResult, error)

GeocodeAndReturnStateLegislativeDistricts will geocode and include State Legislative Districts in the fields response

func (*Geocodio) GeocodeAndReturnTimezone

func (g *Geocodio) GeocodeAndReturnTimezone(address string) (GeocodeResult, error)

GeocodeAndReturnTimezone will geocode and include Timezone in the fields response

func (*Geocodio) GeocodeAndReturnZip4

func (g *Geocodio) GeocodeAndReturnZip4(address string) (GeocodeResult, error)

GeocodeAndReturnZip4 will geocode and include zip4 in the fields response

func (*Geocodio) GeocodeBatch

func (g *Geocodio) GeocodeBatch(addresses ...string) (BatchResponse, error)

GeocodeBatch look up addresses

func (*Geocodio) GeocodeReturnFields

func (g *Geocodio) GeocodeReturnFields(address string, fields ...string) (GeocodeResult, error)

GeocodeReturnFields will geocode and includes additional fields in response

 	See: http://geocod.io/docs/#toc_22
	Note:
		Each field counts as an additional lookup each

func (*Geocodio) Reverse

func (g *Geocodio) Reverse(latitude, longitude float64) (GeocodeResult, error)
See: http://geocod.io/docs/#toc_16

Reverse does a reverse geocode look up for a single coordinate

func (*Geocodio) ReverseBatch

func (g *Geocodio) ReverseBatch(latlngs ...float64) (BatchResponse, error)

ReverseBatch supports a batch lookup by lat/lng coordinate pairs

func (*Geocodio) ReverseGeocode

func (g *Geocodio) ReverseGeocode(latitude, longitude float64) (GeocodeResult, error)

ReverseGeocode is deprecated and will be removed in 2+

type HouseholdIncome

type HouseholdIncome struct {
	Meta                 CensusMeta      `json:"meta"`
	LessThan10000        CensusDataPoint `json:"Less than $10,000"`
	Income10000to14999   CensusDataPoint `json:"$10,000 to $14,999"`
	Income15000to19999   CensusDataPoint `json:"$15,000 to $19,999"`
	Income20000to24999   CensusDataPoint `json:"$20,000 to $24,999"`
	Income25000to29999   CensusDataPoint `json:"$25,000 to $29,999"`
	Income30000to34999   CensusDataPoint `json:"$30,000 to $34,999"`
	Income35000to39999   CensusDataPoint `json:"$35,000 to $39,999"`
	Income40000to44999   CensusDataPoint `json:"$40,000 to $44,999"`
	Income45000to49999   CensusDataPoint `json:"$45,000 to $49,999"`
	Income50000to59000   CensusDataPoint `json:"$50,000 to $59,999"`
	Income60000to74999   CensusDataPoint `json:"$60,000 to $74,999"`
	Income75000to99999   CensusDataPoint `json:"$75,000 to $99,999"`
	Income100000to124999 CensusDataPoint `json:"$100,000 to $124,999"`
	Income125000to149000 CensusDataPoint `json:"$125,000 to $149,999"`
	Income150000to199999 CensusDataPoint `json:"$150,000 to $199,999"`
	Income200000orMore   CensusDataPoint `json:"$200,000 or more"`
}

type Housing

type Housing struct {
	NumberOfHousingUnits            map[string]CensusDataPoint `json:"Number of housing units"`
	OccupancyStatus                 map[string]CensusDataPoint `json:"Occupancy status"`
	OwnershipOfOccupiedUnits        map[string]CensusDataPoint `json:"Ownership of occupied units"`
	UnitsInStructure                map[string]CensusDataPoint `json:"Units in structure"`
	MedianValueOfOwnerOccupiedUnits map[string]CensusDataPoint `json:"Median value of owner-occupied housing units"`
	ValueOfOwnerOccupiedUnits       map[string]CensusDataPoint `json:"Value of owner-occupied housing units"`
}

type Input

type Input struct {
	AddressComponents Components `json:"address_components"`
	FormattedAddress  string     `json:"formatted_address"`
}

type Legislator

type Legislator struct {
	Type       string              `json:"type"`
	Bio        Bio                 `json:"bio"`
	Contact    Contact             `json:"contact"`
	Social     CongressionalSocial `json:"social"`
	References References          `json:"references"`
	Source     string              `json:"source"`
}

Legislator field

{
	"type": "representative",
	"bio": {...},
	"contact": {...},
	"social": {...},
	"references": {...},
	"source": "Legislator data is originally collected and aggregated by https://github.com/unitedstates/"
}

type Location

type Location struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
}

type MedianHouseholdIncome

type MedianHouseholdIncome struct {
	Meta  CensusMeta      `json:"meta"`
	Total CensusDataPoint `json:"Total"`
}

type NumberOfHouseholds

type NumberOfHouseholds struct {
	Meta  CensusMeta      `json:"meta"`
	Total CensusDataPoint `json:"Total"`
}

type Place

type Place struct {
	Name string `json:"name"`
	FIPS string `json:"fips"`
}

type RecordType

type RecordType struct {
	Code        string `json:"code"`
	Description string `json:"description"`
}

type References

type References struct {
	BioguideID       string `json:"bioguide_id"`
	ThomasID         string `json:"thomas_id"`
	OpenSecretsID    string `json:"opensecrets_id"`
	LISID            string `json:"lis_id"`
	CSPANID          string `json:"cspan_id"`
	GovTrackID       string `json:"govtrack_id"`
	VoteSmartID      string `json:"votesmart_id"`
	BallotpediaID    string `json:"ballotpedia_id"`
	WashingtonPostID string `json:"washington_post_id"`
	ICPSRID          string `json:"icpsr_id"`
	WikipediaID      string `json:"wikipedia_id"`
}

References field

"references": {
	"bioguide_id": "B001292",
	"thomas_id": "02272",
	"opensecrets_id": "N00036018",
	"lis_id": null,
	"cspan_id": "21141",
	"govtrack_id": "412657",
	"votesmart_id": "1707",
	"ballotpedia_id": null,
	"washington_post_id": null,
	"icpsr_id": "21554",
	"wikipedia_id": "Don Beyer"
}

type Result

type Result struct {
	Address
	Error *ErrorResponse `json:"response,omitempty"`
}

type SchoolDistrict

type SchoolDistrict struct {
	Name      string `json:"name"`
	LEACode   string `json:"lea_code"`
	GradeLow  string `json:"grade_low"`
	GradeHigh string `json:"grade_high"`
}

SchoolDistrict field

{
	"name": "Desert Sands Unified School District",
	"lea_code": "11110",
	"grade_low": "KG",
	"grade_high": "12"
}

type SchoolDistricts

type SchoolDistricts struct {
	Unified    SchoolDistrict `json:"unified"`
	Elementary SchoolDistrict `json:"elementary"`
	Secondar   SchoolDistrict `json:"secondary"`
}

type Social

type Social struct {
	PopulationByMinimumLevelOfEducation map[string]CensusDataPoint `json:"Population by minimum level of education"`
	PopulationWithVeteran               map[string]CensusDataPoint `json:"Population with veteran status"`
	PeriodOfMilitaryServiceForVeterans  map[string]CensusDataPoint `json:"Period of military service for veterans"`
}

type StateLegislativeDistrict

type StateLegislativeDistrict struct {
	Name           string `json:"name"`
	DistrictNumber string `json:"district_number"`
}

type StateLegislativeDistricts

type StateLegislativeDistricts struct {
	House  StateLegislativeDistrict `json:"house"`
	Senate StateLegislativeDistrict `json:"senate"`
}

type StatisticalArea

type StatisticalArea struct {
	Name     string `json:"name"`
	AreaCode string `json:"area_code"`
	Type     string `json:"type,omitempty"`
}

type Timezone

type Timezone struct {
	Name         string `json:"name"`
	Abbreviation string `json:"abbreviation"` // v1.3+
	UTCOffset    int    `json:"utc_offset"`
	ObservesDST  bool   `json:"observes_dst"`
	Source       string `json:"source"`
}

type Zip4

type Zip4 struct {
	RecodeType         RecordType   `json:"record_type,omitempty"`
	CarrierRoute       CarrierRoute `json:"carrier_route,omitempty"`
	BuildingOrFirmName string       `json:"building_or_firm_name,omitempty"`
	Plus4              []string     `json:"plus4,omitempty"`
	Zip9               []string     `json:"zip9,omitempty"`
	GovermentBuilding  string       `json:"government_building,omitempty"`
	FacilityCode       FacilityCode `json:"facility_code,omitempty"`
	CityDelivery       bool         `json:"city_delivery,omitempty"`
	ValidDeliveryArea  bool         `json:"valid_delivery_area,omitempty"`
	ExactMatch         bool         `json:"exact_match,omitempty"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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