W3W Swift Wrapper

A swift library to use the what3words REST API.

This what3words Swift wrapper gives you programmatic access to the What3Words API version 3.

The what3words API is a fast, simple interface which allows you to convert 3 word addresses such as ///filled.count.soap to latitude and longitude coordinates such as (-0.203586, 51.521251) and vice versa. It features a powerful autosuggest function, which can validate and autocorrect user input and limit it to certain geographic areas (this powers the search box on our map site). It allows you to request a section of the what3words grid (which can be requested as GeoJSON for easy display on online maps), and to request the list of all languages supported by what3words. For advanced users, autosuggest can be used to post-process voice output. See links on the left to navigate.

All coordinates are latitude,longitude pairs in standard WGS-84 (as commonly used worldwide in GPS systems). All latitudes must be in the range of -90 to 90 (inclusive).

Step 1: Obtain an API Key

Sign up to obtain your free API key.

Step 2: Installation

You can install the What3Words API V3 Swift Wrapper Framework into your project using CocoaPods, Carthage, the Swift Package manager, or import the swift code manually. Find it on GitHub.

                        
platform :ios, '9.0'
use_frameworks!

target 'MyApp' do
    pod 'what3words', :git => 'https://github.com/what3words/w3w-swift-wrapper.git'
end
                    
                        
github "what3words/w3w-swift-wrapper"
                    
                        
// include this line in your dependencies:             
.package(url: "https://github.com/what3words/w3w-swift-wrapper.git", .branch("master"))

// include "what3words" in your target dependancies:
dependencies: ["what3words"])

                    
                        
Drag and drop the W3wGeocoder.swift file into your Xcode project.
                    

Step 3: Setup

If you are using it as a framework, import the module as follows in any swift file you wish to use What3Words:

import what3words
import CoreLocation

You must call setup with your API key before you do anything else:

W3wGeocoder.setup(with: "<Secret API Key>")

Step 4: Usage

Convert to 3 word address

Convert a 3 word address to a position, expressed as coordinates of latitude and longitude.

This function takes the words parameter as a string of 3 words 'table.book.chair'

This returns a W3wPlace object. More info about convertTo3wa, including returned results is available in the what3words REST API what3words REST API documentation.

Example: Find the words for (51.520847, -0.195521).
let coords = CLLocationCoordinate2D(latitude: 51.520847, longitude: -0.195521)
W3wGeocoder.shared.convertTo3wa(coordinates: coords) { (place, error) in
    print(place?.words)
}

Convert to Coordinates

To convert coordinates, expressed as latitude and longitude to a 3 word address, call convertToCoordinates. It takes the latitude and longitude as a CLLocationCoordinate2D object.

This returns a W3wPlace object. More info about convertToCoordinates, including returned results is available in the what3words REST API what3words REST API documentation.

Example: Find the cordinates for ///filled.count.soap
W3wGeocoder.shared.convertToCoordinates(words: "filled.count.soap") { (place, error) in
    print(place?.coordinates.latitude, place?.coordinates.longitude)
}

Auto Suggest

When presented with a 3 words 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.

This returns an Array? of W3wSuggestion objects. More info about autosuggest, including returned results is available in the what3words REST API what3words REST API documentation.

Example: Basic call.
W3wGeocoder.shared.autosuggest(input: "fun.with.code") { (suggestions, error) in
    print(suggestions)
}
Example: Limit the search to words in Germany.
W3wGeocoder.shared.autosuggest(input: "geschaft.planter.carciofi", options: ClipToCountry(country:"DE")) { (suggestions, error) in
    print(suggestions)
}
Example: Focus on (51.4243877,-0.34745) and ask for 6 suggestions.
let coords = CLLocationCoordinate2D(latitude: 51.4243877, longitude: -0.34745)
W3wGeocoder.shared.autosuggest(input: "index.raft.ho", options: Focus(focus: coords), NumberResults(numberOfResults: 6) ) { (suggestions, error) in
    print(suggestions)
}

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.

This returns an Array? of W3wLine objects. More info about gridSection, including returned results is available in the what3words REST API what3words REST API documentation.

Example: Get a grid for (52.208867,0.117540) in the south west, and (52.207988,0.116126) in the north east.
W3wGeocoder.shared.gridSection(south_lat: 52.208867, west_lng: 0.117540, north_lat: 52.207988, east_lng: 0.116126) { (lines, error) in
    print(lines)
}

Available Languages

The What3Words system is available in a number of languages. More languages are added all the time, and you ask the API for the current list by calling availableLanguages. This returns an Array? of W3wLanguage objects. More info about availableLanguages, including returned results is available in the what3words REST API what3words REST API documentation.

Example:
W3wGeocoder.shared.availableLanguages() { (languages, error) in
    print(languages)
}

Handling Errors

All functions call the completion block with error as the second parameter. Be sure to check it for possible problems.

Example:
W3wGeocoder.shared.convertToCoordinates(words: "filled.count.soap") { (result, error) in
      if let e = error {
        print(e.code, e.message)
    }
}

Step 5: Putting It All Together

Complete Example using autosuggest to find a place and convertToCoordinates to find it's coordinates:


W3wGeocoder.setup(with: "<Secret API Key>")

let france  = ClipToCountry(country: "FR")
let place   = Focus(focus: CLLocationCoordinate2D(latitude: 48.856618, longitude: 2.3522411))
let count   = NumberResults(numberOfResults: 4)

// Find some suggestions for a partial address
W3wGeocoder.shared.autosuggest(input: "freshen.overlook.clo", options: france, place, count)  { (suggestions, error) in
  
  // if there was an error, print it
  if let e = error {
    print(e.code, e.message)

  // on success print the results
  } else {
    for suggestion in suggestions ?? [] {
      print("\(suggestion.words) is near \(suggestion.nearestPlace) - Country Code:\(suggestion.country)")
    }
  }
  
  // Find coordinates for the first suggestion
  if let suggestion = suggestions?.first {
    print("\nFinding the coordinates for: \(suggestion.words)")

    W3wGeocoder.shared.convertToCoordinates(words: suggestion.words)  { (place, error) in

      // if there was an error, print it
      if let e = error {
        print(e.code, e.message)

      // on success print the result
      } else if let p = place {
        print("The coordinates for \(p.words) are (\(p.coordinates.latitude),\(p.coordinates.longitude))")
      }
    }

  }
  
}
            

Step 6: Further Reading

See the what3words GitHub repository for access to full source code of the this wrapper and further documentation.

Examples of each endpoint are available in the Xcode unit tests provided in the package.