All tutorials
Golang
The Go wrapper is useful for Go developers who wish to seamlessly integrate the what3words Public API into their Go applications, without the hassle of having to manage the low level API calls themselves.
A full example of Go application is available in our GitHub repository.
First, install the Go wrapper by running:
go get github.com/what3words/w3w-go-wrapper
Import the Package
Start by importing the what3words package in your Go code:
import ( "github.com/what3words/w3w-go-wrapper/pkg/apis/v3" what3words "github.com/what3words/w3w-go-wrapper" )
Initialise the Geocoder service
Create a new geocoder instance using your what3words API key. By default, the wrapper will point to the public version of the what3words API.
Public API:
apiKey := "<YOUR_API_KEY>" svc := what3words.NewService(apiKey)
However, if required, the wrapper can be configured to point to a custom endpoint, for example a locally running version of the API. In this case an optional WithCustomBaseURL
parameter can be passed to the what3words.NewService
constructor.
API Server:
svc := what3words.NewService(apiKey, WithCustomBaseURL("http://localhost:8080"))
Convert to what3words address
This function converts coordinates (expressed as latitude and longitude) to a what3words address.
More information about ConvertTo3wa
, including returned results is available in the what3words REST API documentation.
Find the words for (51.520847,-0.195521
):
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.ConvertTo3wa(context.Background(), v3.Coordinates{ Lat: 51.520847, Lng: -0.195521, }, nil) if err != nil { panic(err) } fmt.Println(resp.Json.Words) }
Convert to coordinates
This function converts a what3words address to a position, expressed as coordinates of latitude and longitude.
It takes the words parameter as a string of a what3words 'table.book.chair'
More information about ConvertToCoordinates
, including returned results is available in the what3words REST API documentation.
Find the words for ///filled.count.soap
:
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.ConvertToCoordinates(context.Background(), "filled.count.soap", nil) if err != nil { panic(err) } // By default response JSON is used fmt.Println(resp.Json.Coordinates) // Getting a geojson response geoResp, err := svc.V3().ConvertToCoordinatesGeoJson(context.Background(), "filled.count.soap", nil) if err != nil { panic(err) } // If format GeoJson is not set in options, GeoJson attribute of the response will be set to nil fmt.Println(geoResp.GeoJson.Features[0].Geometry.Coordinates) }
AutoSuggest
When presented with a what3words address which may be incorrectly entered, AutoSuggest returns a list of potential correct 3 word addresses. It needs the first two words plus at least the first character of the third word to produce suggestions.
This method provides corrections for mis-typed words (including plural VS singular), and words being in the wrong order.
Optionally, clipping can narrow down the possibilities, and limit results to:
- One or more countries
- A geographic area (a circle, box or polygon)
This dramatically improves results, so we recommend that you use clipping if possible.
To improve results even further, set the Focus
to user’s current location. This will make AutoSuggest
return results which are closer to the user.
More information about AutoSuggest
, including returned results is available in the what3words REST API documentation.
Code example Simple basic call:
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.AutoSuggest(context.Background(), "filled.count.so") if err != nil { panic(err) } fmt.Println(resp) }
Code example AutoSuggest, clipping the results returned to France and Germany:
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.AutoSuggest(context.Background(), "filled.count.so",&v3.AutoSuggestOpts{ ClipToCountry: []string{"FR", "DE"}, }) if err != nil { panic(err) } fmt.Println(resp) }
Code example AutoSuggest, Focus on (51.4243877,-0.34745
).
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.AutoSuggest(context.Background(), "filled.count.so",&v3.AutoSuggestOpts{ Focus: &core.Coordinates{ Lat: 51.4243877, Lng: -0.34745, }, }) if err != nil { panic(err) } fmt.Println(resp) }
Grid section
Grid section returns a section of the what3words 3m x 3m grid as a set of horizontal and vertical lines covering the requested area, which can then be drawn onto a map.
The requested box must not exceed 4km from corner to corner, or a BadBoundingBoxTooBig
error will be returned.
More information about GridSection
, including returned results is available in the what3words REST API documentation.
Get a grid for 52.207988,0.116126
) in the south west, and 52.208867,0.117540
in the north east:
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.GridSection(context.Background(), v3.BoundingBox{ SouthWest: v3.Coordinates{ Lat: 52.207988, Lng: 0.116126, }, NorthEast: v3.Coordinates{ Lat: 52.208867, Lng: 0.117540, }, }, nil) if err != nil { panic(err) } fmt.Println(resp.Json.Lines) }
Available languages
This function returns the currently supported languages. It will return the two letter code, and the name of the language both in that language and in English.
More information about AvailableLanguages
, including returned results is available in the what3words REST API documentation.
func main() { apiKey := "<YOUR_API_KEY>" svc := w3w.NewService(apiKey) resp, err := svc.V3.AvailableLanguages(context.Background()) if err != nil { panic(err) } fmt.Println(resp) }
Handling errors
In Go, error handling is a fundamental aspect of programming, and the what3words Go wrapper adheres to this convention by returning errors as the second value from its functions. This approach allows developers to handle errors gracefully and implement custom logic based on the error type or message.
Here’s how you can handle errors when using the what3words Go wrapper:
package main import ( "context" "fmt" "log" w3w "github.com/what3words/w3w-go-wrapper" "github.com/what3words/w3w-go-wrapper/pkg/apis/v3" ) func main() { // Initialize the What3Words API with your API key apiKey := "<YOUR_API_KEY>" service := w3w.NewService(apiKey) // Attempt to convert an invalid 3-word address to coordinates address := "garbage.input" resp, err := service.V3.ConvertToCoordinates(context.Background(), address, nil) if err != nil { // Handle the error fmt.Printf("Error converting '%s' to coordinates: %v\n", address, err) return } // If no error, proceed to use the response fmt.Printf("Coordinates for '%s': %+v\n", address, resp.Json.Coordinates) }
Custom Error Handling:
The what3words Go wrapper provides specific error types that can be checked using Go’s errors.As
function. This allows for more granular error handling based on the error type.
package main import ( "context" "errors" "fmt" "log" w3w "github.com/what3words/w3w-go-wrapper" "github.com/what3words/w3w-go-wrapper/pkg/apis/v3" ) func main() { // Initialize the What3Words API with your API key apiKey := "<YOUR_API_KEY>" service := w3w.NewService(apiKey) // Attempt to convert an invalid 3-word address to coordinates address := "garbage.input" resp, err := service.V3.ConvertToCoordinates(context.Background(), address, nil) if err != nil { // Check if the error is of type BadWords var badWordsErr *v3.BadWords if errors.As(err, &badWordsErr) { fmt.Printf("Invalid 3-word address '%s': %s\n", address, badWordsErr.Error()) } else { // Handle other types of errors fmt.Printf("Error converting '%s' to coordinates: %v\n", address, err) } return } // If no error, proceed to use the response fmt.Printf("Coordinates for '%s': %+v\n", address, resp.Json.Coordinates) }
This section introduces RegEx functions that can assist with checking and finding possible what3words addresses in strings. The three main functions covered are:
IsPossible3wa
– Match what3words address format;FindPossible3wa
– Find what3words address in Text;IsValid3wa
– Verify a what3words address with the API;
IsPossible3wa
Our API wrapper RegEx function “IsPossible3wa
” can be used to detect if a text string (like “filled.count.soap
“) in the format of a what3words address without having to ask the API. This functionality checks if a given string could be a what3words address. It returns true if it could be, otherwise false.
Note: This function checks the text format but not the validity of a what3words address. Use IsValid3wa
to verify validity.
package main import ( "fmt" w3w "github.com/what3words/w3w-go-wrapper" ) func main() { // Initialize the What3Words API with your API key apiKey := "<YOUR_API_KEY>" service := w3w.NewService(apiKey) // Example what3words addresses addresses := []string{"filled.count.soap", "not a 3wa", "not.3wa address"} // Check if the addresses are possible what3words addresses for _, address := range addresses { isPossible := service.IsPossible3wa(address) fmt.Printf("Is '%s' a possible what3words address? %t\n", address, isPossible) } }
Expected Output
- IsPossible3wa(“filled.count.soap”) returns
true
- IsPossible3wa(“not a 3wa”) returns
false
- IsPossible3wa(“not.3wa address”)returns
false
FindPossible3wa
Our API wrapper RegEx function “FindPossible3wa
” can be used to detect a what3words address within a block of text, useful for finding a what3words address in fields like Delivery Notes
. For example, it can locate a what3words address in a note like “Leave at my front door ///filled.count.soap
”. The function will match if there is a what3words address within the text. If no possible addresses are found, it returns an empty list.
Note:
- This function checks the text format but not the validity of a what3words address. Use
IsValid3wa
to verify validity. - This function is designed to work across languages but does not work for
Vietnamese (VI)
due to spaces within words.
package main import ( "fmt" w3w "github.com/what3words/w3w-go-wrapper" ) func main() { // Initialize the What3Words API with your API key apiKey := "<YOUR_API_KEY>" service := w3w.NewService(apiKey) // Example texts texts := []string{ "Please leave by my porch at filled.count.soap", "Please leave by my porch at filled.count.soap or deed.tulip.judge", "Please leave by my porch at", } // Check each text for possible what3words addresses for _, text := range texts { possibleAddresses := service.FindPossible3wa(text) fmt.Printf("Possible what3words addresses in '%s': %v\n", text, possibleAddresses) } }
Expected Output
- FindPossible3wa(“Please leave by my porch at filled.count.soap”) returns
['filled.count.soap']
- FindPossible3wa(“Please leave by my porch at filled.count.soap or deed.tulip.judge”) returns
['filled.count.soap', 'deed.tulip.judge']
- FindPossible3wa(“Please leave by my porch at”) returns
[]
isValid3wa
Our API wrapper RegEx function “IsValid3wa
” can be used to determine if a string is a valid what3words address by checking it against the what3words RegEx filter and verifying it with the what3words API.
package main import ( "context" "fmt" w3w "github.com/what3words/w3w-go-wrapper" ) func main() { // Initialize the What3Words API with your API key apiKey := "<YOUR_API_KEY>" service := w3w.NewService(apiKey) // Example addresses addresses := []string{ "filled.count.soap", "filled.count.", "coding.is.cool", } // Check if the addresses are valid what3words addresses for _, address := range addresses { isValid, err := service.IsValid3wa(context.Background(), address) if err != nil { fmt.Printf("Error validating address '%s': %v\n", address, err) } else { fmt.Printf("Is '%s' a valid what3words address? %t\n", address, isValid) } } }
Expected Outputs
- IsValid3wa(“filled.count.soap”) returns
True
- IsValid3wa(“filled.count.”) returns
False
- IsValid3wa(“coding.is.cool”) returns
False
Also, make sure to replace <YOUR_API_KEY>
with your actual API key. These functionalities provide different levels of validation for what3words addresses, from simply identifying potential addresses to verifying their existence on Earth.
If you encounter errors or issues related to convert-to-coordinate requests while using the Free plan, please check the network panel for the following error message Error 402 payment required
and its response, indicating the need to upgrade to a higher plan:
{ "error": { "code": "QuotaExceeded", "message": "Quota Exceeded. Please upgrade your usage plan, or contact support@what3words.com" } }
For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.