geocoder

package module
v0.0.0-...-0a8a678 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2019 License: MIT Imports: 8 Imported by: 10

README

Mapquest geocoder and directions for Go (golang)

What it does

  • Returns a Longitude and Latitude for a given string query
  • Returns an address for a Longitude and Longitude
  • Returns directions between two or more points. (JSON or XML)

API Key

Get a free API Key at http://mapquestapi.com.

Why MapQuest API?

Google Maps Geocoding API has a limitation that prohibits querying their geocoding API unless you will be displaying the results on a Google Map. Google directions is limited to 2 requests per second. MapQuest's geocoding API does not have these restrictions.

Installation

  • go get "github.com/jasonwinn/geocoder"
  • import "github.com/jasonwinn/geocoder"

Examples

Set API Key

You'll want to set an api key for the Mapquest API to go into production.

// this is the testing key used in `go test`
SetAPIKey("Fmjtd%7Cluub256alu%2C7s%3Do5-9u82ur")
Geocode

To retrieve just the latitude and longitude of the best match for a particular query, use the Geocode method:

  query := "Seattle WA"
  lat, lng, err := geocoder.Geocode(query)
  if err != nil {
    panic("THERE WAS SOME ERROR!!!!!")
  }
  
  // 47.6064, -122.330803
 

To retrieve a full geocoding result including all matches as well as additional location information per match like the street, city and state, use the FullGeocode method:

  query := "Seattle WA"
  result, err := geocoder.FullGeocode(query)
  if err != nil {
    panic("THERE WAS SOME ERROR!!!!!")
  }
  
  // GeocodingResult instance
 
Reverse Geocode
  address, err := geocoder.ReverseGeocode(47.6064, -122.330803)
  if err != nil {
    panic("THERE WAS SOME ERROR!!!!!")
  }

  address.Street 	        // 542 Marion St   
  address.City 		        // Seattle
  address.State 	        // WA
  address.PostalCode 	    // 98104 
  address.County 	        // King
  address.CountryCode       // US 

Directions
  directions := NewDirections("Amsterdam,Netherlands", []string{"Antwerp,Belgium"})
  results, err := directions.Get()
  if err != nil {
    panic("THERE WAS SOME ERROR!!!!!")
  }

  route := results.Route
  time := route.Time
  legs := route.Legs
  distance := route.Distance

  // or get distance with this shortcut
  //
  // use "k" to return result in km
  // use "m" to return result in miles
  distance, err := directions.Distance("k")
  if err != nil {
    panic("THERE WAS SOME ERROR!!!!!")
  }

Documentation

https://godoc.org/github.com/jasonwinn/geocoder

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Geocode

func Geocode(address string) (float64, float64, error)

Returns the latitude and longitude of the best location match for the specified query.

func SetAPIKey

func SetAPIKey(key string)

SetAPIKey lets you set your own api key. The default api key is probably okay to use for testing. But for production, you should create your own key at http://mapquestapi.com

Types

type Directions

type Directions struct {
	// Starting location
	From string
	// Ending location
	To []string
	// type of units for calculating distance: m (Miles, default) or k (Km)
	Unit string
	// fastest(default), shortest, pedestrian, multimodal, bicycle
	RouteType string
	// If true(default), reverse geocode call will be performed even on lat/long.
	DoReverseGeocode bool
	// none, text(default), html, microformat
	NarrativeType string
	// Encompass extra advice such as intersections (default false)
	EnhancedNarrative bool
	// The maximum number of Link IDs to return for each maneuver (default is 0)
	MaxLinkID int
	// en_US(default), en_GB, fr_CA, fr_FR, de_DE, es_ES, es_MX, ru_RU
	Locale string
	// Limited Access, Toll Road, Ferry, Unpaved, Seasonal Closure, Country Crossing
	Avoids []string
	// Link IDs of roads to absolutely avoid. May cause some routes to fail.
	MustAvoidLinkIDs []int
	// Link IDs of roads to try to avoid during route calculation without guarantee.
	TryAvoidLinkIDs []int
	// Whether state boundary crossings will be displayed in narrative. (default true)
	StateBoundaryDisplay bool
	// Whether country boundary crossings will be displayed in narrative. (default true)
	CountryBoundaryDisplay bool
	// Whether "End at" destination maneuver will be displayed in narrative. (default true)
	DestinationManeuverDisplay bool
	// To return a route shape without a mapState. (default false)
	FullShape bool
	// A value of < 1 favors cycling on non-bike lane roads. [0.1..1(default)..100]
	CyclingRoadFactor float64
	// DEFAULT_STRATEGY (default), AVOID_UP_HILL, AVOID_DOWN_HILL,AVOID_ALL_HILLS,FAVOR_UP_HILL,FAVOR_DOWN_HILL,FAVOR_ALL_HILLS
	RoadGradeStrategy string
	// cautious, normal, aggressive
	DrivingStyle string
	// Fuel efficiency, given as miles per gallon. (0..235 mpg)
	HighwayEfficiency float64
	// If true (default), a small staticmap is displayed per maneuver
	ManMaps bool
	// Walking speed, always in miles per hour independent from unit (default 2.5)
	WalkingSpeed float64
	// Session id
	SessionID string
}

Directions provide information on how to get from one location to one (or more) other locations together with copyright and statuscode info. (style, shape and mapstate options are not implemented)

func NewDirections

func NewDirections(from string, to []string) *Directions

NewDirections is a constructor to initialize a Directions struct with mapquest defaults.

func (Directions) Distance

func (directions Directions) Distance(unit string) (distance float64, err error)

Distance calculated in km or miles (unit is k [km] or m [miles])

func (Directions) Dump

func (directions Directions) Dump(format string) (data []byte, err error)

Dump directions as undecoded json or xml bytes

func (Directions) Get

func (directions Directions) Get() (results *DirectionsResults, err error)

Get the Direction Results (Route & Info)

func (Directions) URL

func (directions Directions) URL(format string) string

URL constructs the mapquest directions url (format is json or xml)

type DirectionsResults

type DirectionsResults struct {
	Route Route `json:"route"`
	Info  Info  `json:"info"`
}

DirectionsResults can be decoded from the Directions route response

type DistanceResults

type DistanceResults struct {
	Route struct {
		Distance float64 `json:"distance"`
	} `json:"route"`
	Info Info `json:"info"`
}

DistanceResults json struct to retrieve only the distance

type GeocodingResult

type GeocodingResult struct {
	Info    Info `json:"info"`
	Options struct {
		MaxResults        int  `json:"maxResults"`
		ThumbMaps         bool `json:"thumbMaps"`
		IgnoreLatLngInput bool `json:"ignoreLatLngInput"`
	} `json:"options"`
	Results []struct {
		ProvidedLocation struct {
			Location string `json:"location"`
		} `json:"providedLocation"`
		Locations []struct {
			Street string `json:"street"`
			// Neighborhood
			AdminArea6     string `json:"adminArea6"`
			AdminArea6Type string `json:"adminArea6Type"`
			// City
			AdminArea5     string `json:"adminArea5"`
			AdminArea5Type string `json:"adminArea5Type"`
			// County
			AdminArea4     string `json:"adminArea4"`
			AdminArea4Type string `json:"adminArea4Type"`
			// State
			AdminArea3     string `json:"adminArea3"`
			AdminArea3Type string `json:"adminArea3Type"`
			// Country
			AdminArea1         string `json:"adminArea1"`
			AdminArea1Type     string `json:"adminArea1Type"`
			PostalCode         string `json:"postalCode"`
			GeocodeQualityCode string `json:"geocodeQualityCode"`
			// ex: "NEIGHBORHOOD", "CITY", "COUNTY"
			GeocodeQuality string `json:"geocodeQuality"`
			DragPoint      bool   `json:"dragPoint"`
			SideOfStreet   string `json:"sideOfStreet"`
			LinkId         string `json:"linkId"`
			UnknownInput   string `json:"unknownInput"`
			Type           string `json:"type"`
			LatLng         LatLng `json:"latLng"`
			DisplayLatLng  LatLng `json:"displayLatLng"`
			MapUrl         string `json:"mapUrl"`
		} `json:"locations"`
	} `json:"results"`
}

Complete geocoding result

func FullGeocode

func FullGeocode(address string) (*GeocodingResult, error)

Returns the full geocoding response including all of the matches as well as reverse-geocoded for each match location.

type Info

type Info struct {
	Copyright struct {
		Text         string `json:"text"`         // "© 2014 MapQuest, Inc."
		ImageURL     string `json:"imageUrl"`     // "http://api.mqcdn.com/res/mqlogo.gif"
		ImageAltText string `json:"imageAltText"` // "© 2014 MapQuest, Inc."
	} `json:"copyright"`
	Statuscode int      `json:"statuscode"`
	Messages   []string `json:"messages"`
}

Info about copyright and statuscode

func (Info) Error

func (err Info) Error() string

type LatLng

type LatLng struct {
	Lat float64 `json:"lat"`
	Lng float64 `json:"lng"`
}

LatLng specifies a point with latitude and longitude

func BatchGeocode

func BatchGeocode(addresses []string) ([]LatLng, error)

Geocodes multiple locations with a single API request. Up to 100 locations per call may be provided.

type Leg

type Leg struct {
	// The shape point index which starts a specific route segment.
	Index int `json:"index"`
	// Returns true if at least one maneuver contains a Toll Road.
	HasTollRoad bool `json:"hasTollRoad"`
	// Returns true if at least one maneuver contains a Limited Access/Highway.
	HasHighway bool `json:"hasHighway"`
	// Returns true if at least one maneuver contains a Seasonal Closure.
	HasSeasonalClosure bool `json:"hasSeasonalClosure"`
	// Returns true if at least one maneuver contains an Unpaved.
	HasUnpaved bool `json:"hasUnpaved"`
	// Returns true if at least one maneuver contains a Country Crossing.
	HasCountryCross bool `json:"hasCountryCross"`
	// Returns the calculated elapsed time in seconds for the leg.
	Time int `json:"time"`
	// Returns the calculated elapsed time as formatted text in HH:MM:SS format.
	FormattedTime string `json:"formattedTime"`
	// Returns the calculated distance of the leg.
	Distance float64 `json:"distance"`
	// A collection of Maneuver objects
	Maneuvers []Maneuver `json:"maneuvers"`
	// Road grade avoidance strategies
	RoadGradeStrategy [][]int `json:"roadGradeStrategy"`

	// The origin index is the index of the first non-collapsed maneuver.
	OrigIndex int `json:"origIndex"`
	//  The rephrased origin narrative string for the first non-collapsed maneuver.
	OrigNarrative string `json:"origNarrative"`
	// The destination index is the index of the last non-collapsed maneuver.
	DestIndex int `json:"destIndex"`
	// The rephrased destination narrative string for the destination maneuver.
	DestNarrative string `json:"destNarrative"`
}

Leg contains the maneuvers describing how to get from one location to the next location. Multiple legs belong to a route.

type Location

type Location struct {
	Street      string `json:"street"`
	City        string `json:"adminArea5"`
	State       string `json:"adminArea3"`
	PostalCode  string `json:"postalCode"`
	County      string `json:"adminArea4"`
	CountryCode string `json:"adminArea1"`
	LatLng      LatLng `json:"latLng"`
	Type        string `json:"type"`
	DragPoint   bool   `json:"dragPoint"`
}

Location is specified by its address and coordinates

func ReverseGeocode

func ReverseGeocode(lat float64, lng float64) (*Location, error)

Returns the address for a latitude and longitude.

type Maneuver

type Maneuver struct {
	Index int `json:"index"`
	// Returns the calculated elapsed time in seconds for the maneuver.
	Time int `json:"time"`
	// Returns the calculated elapsed time as formatted text in HH:MM:SS format.
	FormattedTime string `json:"formattedTime"`
	// Returns the calculated distance of the maneuver.
	Distance float64 `json:"distance"`
	// Text name, extra text, type (road shield), direction and image
	Signs []Sign `json:"signs"`
	// An URL to a static map of this maneuver.
	MapURL string `json:"mapUrl"`
	// Textual driving directions for a particular maneuver.
	Narrative string `json:"narrative"`
	/* // A collection of maneuverNote objects, one for each maneuver.
	   ManeuverNotes []ManeuverNote `json:"maneuverNotes"` */
	// none=0,north=1,northwest=2,northeast=3,south=4,southeast=5,southwest=6,west=7,east=8
	Direction int `json:"direction"`
	// Name of the direction
	DirectionName string `json:"directionName"`
	// Collection of street names this maneuver applies to
	Streets []string `json:"streets"`
	// none=0,portions toll=1,portions unpaved=2,possible seasonal road closure=4,gate=8,ferry=16,avoid id=32,country crossing=64,limited access (highways)=128
	Attributes int `json:"attributes"`
	// straight=0,slight right=1,right=2,sharp right=3,reverse=4,sharp left=5,left=6,slight left=7,right u-turn=8,
	// left u-turn=9,right merge=10,left merge=11,right on ramp=12,left on ramp=13,right off ramp=14,left off ramp=15,right fork=16,left fork=17,straight fork=18
	TurnType int `json:"direction"`
	// 1st shape point latLng for a particular maneuver (eg for zooming)
	StartPoint LatLng `json:"startPoint"`
	// Icon
	IconURL string `json:"iconUrl"`
	// "AUTO", "WALKING", "BICYCLE", "RAIL", "BUS" (future use)
	TransportMode string `json:"transportMode"`
	// Link Ids of roads
	LinkIDs []int `json:"linkIds"`
}

Maneuver describes each one step in a route narrative. Multiple maneuvers belong to a leg.

type Route

type Route struct {
	// Returns true if at least one leg contains a Toll Road.
	HasTollRoad bool `json:"hasTollRoad"`
	// Returns true if at least one leg contains a Limited Access/Highway.
	HasHighway bool `json:"hasHighway"`
	// Returns true if at least one leg contains a Seasonal Closure.
	HasSeasonalClosure bool `json:"hasSeasonalClosure"`
	// Returns true if at least one leg contains an Unpaved.
	HasUnpaved bool `json:"hasUnpaved"`
	// Returns true if at least one leg contains a Country Crossing.
	HasCountryCross bool `json:"hasCountryCross"`
	// Returns lat/lng bounding rectangle of all points
	BoundingBox struct {
		UpperLeft  LatLng `json:"ul"`
		LowerRight LatLng `json:"lr"`
	} `json:"BoundingBox"`
	// Returns the calculated elapsed time in seconds for the route.
	Time int `json:"time"`
	// Returns the calculated elapsed time as formatted text in HH:MM:SS format.
	FormattedTime string `json:"formattedTime"`
	// Returns the calculated distance of the route.
	Distance float64 `json:"distance"`
	// The estimated amount of fuel used during the route
	FuelUsed float64 `json:"fuelUsed"`
	// A collection of leg objects, one for each "leg" of the route.
	Legs []Leg `json:"legs"`
	// Error report
	RouteError struct {
		Message   string `json:"message"`
		ErrorCode int    `json:"errorCode"`
	} `json:"routeError"`
	// A collection of locations in the form of an address.
	Locations []Location `json:"locations"`
	// Location sequence
	LocationSequence []int `json:"locationSequence"`
	// A unique identifier used to refer to a session
	SessionID string `json:"sessionId"`
}

Route provides information on how to get from one location to one (or more) other locations.

type Sign

type Sign struct {
	Text      string `json:"text"`
	ExtraText string `json:"extraText"`
	Direction int    `json:"direction"`
	// road shield
	Type int `json:"type"`
	// Image
	URL string `json:"url"`
}

Sign specifies information for a particular maneuver.

Jump to

Keyboard shortcuts

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