rgeo

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2025 License: Apache-2.0 Imports: 14 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

rgeo fork

This is a fork of https://github.com/sams96/rgeo with

  • modified data format for 30x faster startup, and
  • snapping functionality, so that e.g. lookups near coastlines succeed heuristically.

Rgeo is a fast, simple solution for local reverse geocoding, Rather than relying on external software or online APIs, rgeo packages all of the data it needs in your binary. This means it will only ever work down to the level of cities , but if that's all you need then this is the library for you.

Rgeo uses data from naturalearthdata.com, if your coordinates are going to be near specific borders I would advise checking the data beforehand (links to which are in the files). If you want to use your own dataset, check out datagen.

Key Features

  • Fast - So I haven't actually benchmarked other reverse geocoding tools but on my laptop rgeo can run at under 800ns/op.
  • Local - Rgeo doesn't require pinging some API, most of which either cost money to use or have severe rate limits.
  • Lightweight - The rgeo repo is 32MB, which is large for a Go package but compared to the 800GB needed for a full planet install of Nominatim it's miniscule.

Installation

Download with

go get github.com/authenticvision/rgeo

and add

import "github.com/authenticvision/rgeo"

to the top of your Go file to include it in your project.

Usage

r, err := New(Provinces10, Cities10)
if err != nil {
	// Handle error
}

loc, err := r.ReverseGeocode([]float64{141.35, 43.07})
if err != nil {
	// Handle error
}

fmt.Println(loc)
// Output: <Location> Sapporo, Hokkaidō, Japan (JPN), Asia

First initialise rgeo using rgeo.New,

func New(datasets ...func() []byte) (*Rgeo, error)

which takes any non-zero number of datasets as arguments. The included datasets are:

  • Countries110 - Just country information, smallest and lowest detail of the included datasets.
  • Countries10 - The same as above but with more detail.
  • Provinces10 - Includes province information as well as country, so can still be used alone.
  • Cities10 - Just city information, if you want provinces and/or countries as well use one of the above datasets with it. Once initialised you can use ReverseGeocode on the value returned by New, with your coordinates to get the location information. See the Go Docs for more information on usage.

Then use ReverseGeocode to get the location information of the given coordinate.

func (r *Rgeo) ReverseGeocode(loc geom.Coord) (Location, error)

The input is a geom.Coord, which is just a []float64 with the longitude in the zeroth position and the latitude in the first position (i.e. []float64{lon, lat}). ReverseGeocode returns a Location, which looks like this:

type Location struct {
	// Commonly used country name
	Country string `json:"country,omitempty"`

	// Formal name of country
	CountryLong string `json:"country_long,omitempty"`

	// ISO 3166-1 alpha-1 and alpha-2 codes
	CountryCode2 string `json:"country_code_2,omitempty"`
	CountryCode3 string `json:"country_code_3,omitempty"`

	Continent string `json:"continent,omitempty"`
	Region    string `json:"region,omitempty"`
	SubRegion string `json:"subregion,omitempty"`

	Province string `json:"province,omitempty"`

	// ISO 3166-2 code
	ProvinceCode string `json:"province_code,omitempty"`

	City string `json:"city,omitempty"`
}

So, to put it all together:

r, err := rgeo.New(Countries110)
if err != nil {
	// Handle error
}

loc, err := r.ReverseGeocode([]float64{0, 52})
if err != nil {
	// Handle error
}

fmt.Printf("%s\n", loc.Country)
fmt.Printf("%s\n", loc.CountryLong)
fmt.Printf("%s\n", loc.CountryCode2)
fmt.Printf("%s\n", loc.CountryCode3)
fmt.Printf("%s\n", loc.Continent)
fmt.Printf("%s\n", loc.Region)
fmt.Printf("%s\n", loc.SubRegion)

// Output: United Kingdom
// United Kingdom of Great Britain and Northern Ireland
// GB
// GBR
// Europe
// Europe
// Northern Europe
Data inaccuracy

If you have troubles resolving the location of the coordinates due to GPS and/or data inaccuracy (e.g. at the coast, GPS might give you coordinates of a location several meters out in the water) you can use ReverseGeocodeSnapping instead of ReverseGeocode.

func (r *Rgeo) ReverseGeocodeSnapping(loc geom.Coord) (Location, error)

It first tries to find the location using ReverseGeocode and only if that fails, it will look up the closest location in a default radius of 5km. This radius can be set via the SetSnappingDistanceEarth and SetSnappingDistanceCustom functions.

func (r *Rgeo) SetSnappingDistanceEarth(d float64)
func (r *Rgeo) SetSnappingDistanceCustom(d float64, radius float64)

SetSnappingDistanceEarth takes the radius float64 in km, which is the search radius of the alternative location. If the dataset contains geo-data of a sphere that has different dimensions than earth, use SetSnappingDistanceCustom with the distance d float64 in the same units used for the radius of the sphere.

Contributing

This is an internally used fork of https://github.com/sams96/rgeo. We do not intend for this to become the new upstream, but it seems to be the only active fork at the time of writing. Please check the original author's blog post for details: https://sams96.github.io/rgeo-5-years-on/.

We will continue to maintain and use this project for the time being, because alternatives require sqlite3 in Go, which -- due to their C dependencies or per platform source to source compilation - results in non-portable projects with fragile package interdependencies.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrLocationNotFound = errors.New("country not found")

ErrLocationNotFound is returned when no country is found for given coordinates.

Functions

This section is empty.

Types

type Dataset

type Dataset func() []Feature

Dataset provides a Feature slice. It is a function for easier integration into existing rgeo v1 code only.

type Feature

type Feature struct {
	Location Location
	Polygon  *s2.Polygon
}

func Cities10

func Cities10() []Feature

func Countries10

func Countries10() []Feature

func Countries110

func Countries110() []Feature

func LoadEncoded

func LoadEncoded(r io.Reader) ([]Feature, error)

func Provinces10

func Provinces10() []Feature

func (*Feature) Decode

func (f *Feature) Decode(r io.Reader) error

func (*Feature) Encode

func (f *Feature) Encode(w io.Writer) error

type FeatureCollection

type FeatureCollection []Feature

func (*FeatureCollection) Encode

func (fc *FeatureCollection) Encode(w io.Writer) error

type Location

type Location struct {
	// Commonly used country name
	Country string `json:"country,omitempty"`

	// Formal name of country
	CountryLong string `json:"country_long,omitempty"`

	// ISO 3166-1 alpha-1 and alpha-2 codes
	CountryCode2 string `json:"country_code_2,omitempty"`
	CountryCode3 string `json:"country_code_3,omitempty"`

	Continent string `json:"continent,omitempty"`
	Region    string `json:"region,omitempty"`
	SubRegion string `json:"subregion,omitempty"`

	Province string `json:"province,omitempty"`

	// ISO 3166-2 code
	ProvinceCode string `json:"province_code,omitempty"`

	City string `json:"city,omitempty"`
}

Location is the return type for ReverseGeocode.

func (Location) String

func (l Location) String() string

String method for type Location.

type Rgeo

type Rgeo struct {
	// contains filtered or unexported fields
}

Rgeo is the type used to hold pre-created polygons for reverse geocoding.

func New

func New(datasets ...Dataset) (*Rgeo, error)

New returns a Rgeo struct which can then be used with ReverseGeocode. It takes any number of datasets as arguments.

The included datasets are:

  • Cities10
  • Countries10
  • Countries110
  • Provinces10

func (*Rgeo) Build

func (r *Rgeo) Build()

Build builds the underlying shape index. This ensures that future calls to ReverseGeocode will be fast. If Build is not called, then the first lookup will build the index implicitly and experience a 1s+ delay.

func (*Rgeo) ReverseGeocode

func (r *Rgeo) ReverseGeocode(loc geom.Coord) (Location, error)

ReverseGeocode returns the country in which the given coordinate is located.

The input is a geom.Coord, which is just a []float64 with the longitude in the zeroth position and the latitude in the first position (i.e. []float64{lon, lat}).

Example
r, err := New(Countries110)
if err != nil {
	// Handle error
}

loc, err := r.ReverseGeocode([]float64{0, 52})
if err != nil {
	// Handle error
}

fmt.Printf("%s\n", loc.Country)
fmt.Printf("%s\n", loc.CountryLong)
fmt.Printf("%s\n", loc.CountryCode2)
fmt.Printf("%s\n", loc.CountryCode3)
fmt.Printf("%s\n", loc.Continent)
fmt.Printf("%s\n", loc.Region)
fmt.Printf("%s\n", loc.SubRegion)
Output:
United Kingdom
United Kingdom of Great Britain and Northern Ireland
GB
GBR
Europe
Europe
Northern Europe
Example (City)
r, err := New(Provinces10, Cities10)
if err != nil {
	// Handle error
}

loc, err := r.ReverseGeocode([]float64{141.35, 43.07})
if err != nil {
	// Handle error
}

fmt.Println(loc)
Output:
<Location> Sapporo, Hokkaidō, Japan (JPN), Asia
Example (Snapping)
r, err := New(Provinces10)
if err != nil {
	// Handle error
}

loc, err := r.ReverseGeocodeSnapping(geom.Coord{141.5439, 40.5588})
if err != nil {
	// Handle error
}

fmt.Println(loc)
Output:
<Location> Aomori, Japan (JPN), Asia

func (*Rgeo) ReverseGeocodeSnapping

func (r *Rgeo) ReverseGeocodeSnapping(coord geom.Coord) (Location, error)

func (*Rgeo) SetSnappingDistanceCustom

func (r *Rgeo) SetSnappingDistanceCustom(d float64, radius float64)

SetSnappingDistanceCustom recalculates the underlying ChordAngle for the DistanceLimit of nearest-edge queries via ReverseGeocodeSnapping.

The inputs are the snapping distance on the sphere's surface in kilometers, and the radius of the sphere used in the dataset.

func (*Rgeo) SetSnappingDistanceEarth

func (r *Rgeo) SetSnappingDistanceEarth(d float64)

SetSnappingDistanceEarth sets ReverseGeocodeSnapping snap distance on Earth. Only edges within the defined radius around given points will be considered by ReverseGeocodeSnapping.

The input is the snapping distance in kilometers. Must be positive.

Directories

Path Synopsis
cmd
datagen command
Command datagen converts GeoJSON files into go files containing functions that return the compressed GeoJSON, it can also merge properties from one GeoJSON file into another using the -merge flag (which it does by matching the country names).
Command datagen converts GeoJSON files into go files containing functions that return the compressed GeoJSON, it can also merge properties from one GeoJSON file into another using the -merge flag (which it does by matching the country names).

Jump to

Keyboard shortcuts

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