Uma biblioteca JavaScript para fazer solicitações para a API REST WHAT3WORDS. Agora, com melhor suporte para uso em ambientes baseados em navegador e nó! Consulte a documentação da API pública What3Words para obter mais informações sobre como usar nossa API REST.
O What3Words JavaScript Wrapper oferece acesso programático a:
NPM:
npm install @what3words/api
fio:
yarn add @what3words/api
Se você deseja usar os transportes internos, também precisará instalar as dependências de pares para eles. Para obter mais informações sobre os transportes padrão, leia a seção sobre transportes.
const what3words ,
{ fetchTransport } = require ( '@what3words/api' ) ;
const apiKey = '<YOUR_API_KEY>' ;
const config = {
host : 'https://api.what3words.com' ,
apiVersion : 'v3' ,
} ;
const transport = fetchTransport ( ) ; // or you can import 'axiosTransport' instead
const w3wService = what3words ( apiKey , config , { transport } ) ;
// you can uncomment the following lines to set your api key and config after instantiation of the w3w service
// w3wService.setApiKey(apiKey);
// w3wService.setConfig(config);
import what3words , {
ApiVersion ,
Transport ,
What3wordsService ,
axiosTransport ,
} from '@what3words/api' ;
const apiKey = '<YOUR_API_KEY>' ;
const config : {
host : string ;
apiVersion : ApiVersion ;
} = {
host : 'https://api.what3words.com' ,
apiVersion : ApiVersion . Version3 ,
} ;
const transport : Transport = axiosTransport ( ) ;
const w3wService : What3wordsService = what3words ( apiKey , config , { transport } ) ;
// code continues...
O What3wordsService
fornece uma maneira rápida e fácil de instanciar os clientes da API que podem ser usados para fazer solicitações contra a API What3Words. Ele também fornece funções auxiliares para definir a configuração da API, como a versão do host e da API e sua chave da API nos clientes da API What3Words.
Os clientes da API What3Words nesta biblioteca são usados para validar opções de solicitação, serializar e manipular solicitação/resposta e erros contra um terminal de API. Cada cliente estende a classe ApiClient
abstrata.
Existe um cliente específico para cada solicitação e você pode usá -lo independentemente do What3wordsService
. Isso pode ser particularmente útil se você deseja estender o comportamento do cliente, minimizar seu código ou, em um exemplo mais extremo, usar um transporte personalizado para lidar com solicitações de maneira diferente em cada cliente.
Todo cliente aceita os seguintes parâmetros:
Parâmetro | Datatype | Valor padrão |
---|---|---|
APIKEY | corda | '' |
Config | config.host | https://api.what3words.com |
config.Apiversion | v3 |
O transporte é uma função responsável por executar a solicitação em relação à API. Dado um ClientRequest
o transporte deve devolver uma promessa que resolve a TransportResponse
.
Um ClientRequest
consiste nas seguintes propriedades:
Propriedade | Datatype |
---|---|
hospedar * | string |
url * | string |
método * | get ou post |
consulta | object |
cabeçalhos | object |
corpo | object |
formato * | json ou geojson . Padrão: json |
Uma TransportResponse
consiste nas seguintes propriedades:
Propriedade | Datatype |
---|---|
status * | number |
statustext * | string |
corpo * | any |
cabeçalhos | object |
Existem dois transportes embutidos disponíveis com esta biblioteca que você pode usar; arremesso cruzado ou axios. Ao especificar qual transporte você gostaria de usar na inicialização do What3wordsService
ou de um cliente, se desejar instanciar um cliente para si mesmo.
Existem dois transportes internos disponíveis:
Para usar qualquer um deles, você precisará instalar a dependência dos colegas. Por padrão, a busca cruzada é assumida pelo What3wordsService
ou por qualquer cliente instanciado, onde nenhuma substituição é fornecida.
NPM:
npm install cross-fetch
ou
npm install axios
fio:
yarn add cross-fetch
ou
yarn add axios
Você pode fornecer seu próprio transporte personalizado, se desejar usar outra biblioteca para lidar com solicitações, o que pode ser útil se você tiver outras integrações ou já estiver usando uma biblioteca HTTP em outro lugar.
Para fazer isso, você precisa definir seu próprio Transport
e passá -lo para o What3wordsService
ou o cliente para usá -lo.
O Transport
personalizado que você cria deve ser uma função que aceita um ClientRequest
como um argumento e retorna uma promessa que resolve uma TransportResponse
.
import what3words , { ClientRequest , TransportResponse } from '@what3words/api' ;
import superagent from 'superagent' ;
const API_KEY = '<YOUR_API_KEY>' ;
const config = { } ; // This will ensure we do not override the defaults
function customTransport < ResponseType > (
request : ClientRequest
) : Promise < TransportResponse < ResponseType > > {
const {
method ,
host ,
url ,
query = { } ,
headers = { } ,
body = { } ,
format ,
} = request ;
return new Promise ( resolve =>
superagent [ method ] ( ` ${ host } ${ url } ` )
. query ( { ... query , format } )
. send ( body || { } )
. set ( headers )
. end ( ( err , res ) => {
if ( err || ! res )
return resolve ( {
status : err . status || 500 ,
statusText : err . response . text || 'Internal Server Error' ,
headers : err . headers || { } ,
body : err . response . text || null ,
} ) ;
const response : TransportResponse < ResponseType > = {
status : res . status ,
statusText : res . text ,
headers : res . headers ,
body : res . body ,
} ;
resolve ( response ) ;
} )
) ;
}
const service = what3words ( API_KEY , config , { transport : customTransport } ) ;
service
. availableLanguages ( )
. then ( ( { languages } ) => console . log ( 'Available languages' , languages ) ) ;
import {
AutosuggestClient ,
AutosuggestOptions ,
AutosuggestResponse ,
} from '@what3words/api' ;
const API_KEY = '<YOUR_API_KEY>' ;
const client : AutosuggestClient = AutosuggestClient . init ( API_KEY ) ;
const options : AutosuggestOptions = {
input : 'filled.count.s' ,
} ;
client
. run ( options )
. then ( ( res : AutosuggestResponse ) =>
console . log ( `suggestions for " ${ options . input } "` , res )
) ;
import {
ConvertToCoordinatesClient ,
ConvertToCoordinatesOptions ,
FeatureCollectionResponse ,
LocationGeoJsonResponse ,
LocationJsonResponse ,
} from '@what3words/api' ;
const API_KEY = '<YOUR_API_KEY>' ;
const client : ConvertToCoordinatesClient =
ConvertToCoordinatesClient . init ( API_KEY ) ;
const options : ConvertToCoordinatesOptions = { words : 'filled.count.soap' } ;
// If you want to retrieve the JSON response from our API
client
. run ( { ... options , format : 'json' } ) // { format: 'json' } is the default response
. then ( ( res : LocationJsonResponse ) =>
console . log ( 'Convert to coordinates' , res )
) ;
// If you want to retrieve the GeoJsonResponse from our API
client
. run ( { ... options , format : 'geojson' } )
. then ( ( res : FeatureCollectionResponse < LocationGeoJsonResponse > ) =>
console . log ( 'Convert to coordinates' , res )
) ;
import {
ConvertTo3waClient ,
ConvertTo3waOptions ,
FeatureCollectionResponse ,
LocationGeoJsonResponse ,
LocationJsonResponse ,
} from '@what3words/api' ;
const API_KEY = '<YOUR_API_KEY>' ;
const client : ConvertTo3waClient = ConvertTo3waClient . init ( API_KEY ) ;
const options : ConvertTo3waOptions = {
coordinates : { lat : 51.520847 , lng : - 0.195521 } ,
} ;
// If you want to retrieve the JSON response from our API
client
. run ( { ... options , format : 'json' } ) // { format: 'json' } is the default response
. then ( ( res : LocationJsonResponse ) => console . log ( 'Convert to 3wa' , res ) ) ;
// If you want to retrieve the GeoJsonResponse from our API
client
. run ( { ... options , format : 'geojson' } )
. then ( ( res : FeatureCollectionResponse < LocationGeoJsonResponse > ) =>
console . log ( 'Convert to 3wa' , res )
) ;
import {
AvailableLanguagesClient ,
AvailableLanguagesResponse ,
} from '@what3words/api' ;
const API_KEY = '<YOUR_API_KEY>' ;
const client : AvailableLanguagesClient = AvailableLanguagesClient . init ( API_KEY ) ;
client
. run ( )
. then ( ( res : AvailableLanguagesResponse ) =>
console . log ( 'Available Languages' , res )
) ;
import {
GridSectionClient ,
GridSectionOptions ,
FeatureCollectionResponse ,
GridSectionGeoJsonResponse ,
GridSectionJsonResponse ,
} from '../src' ;
const API_KEY = '<YOUR_API_KEY>' ;
const client : GridSectionClient = GridSectionClient . init ( API_KEY ) ;
const options : GridSectionOptions = {
boundingBox : {
southwest : { lat : 52.208867 , lng : 0.11754 } ,
northeast : { lat : 52.207988 , lng : 0.116126 } ,
} ,
} ;
// If you want to retrieve the JSON response from our API
client
. run ( { ... options , format : 'json' } ) // { format: 'json' } is the default response
. then ( ( res : GridSectionJsonResponse ) => console . log ( 'Grid Section' , res ) ) ;
// If you want to retrieve the JSON response from our API
client
. run ( { ... options , format : 'geojson' } ) // { format: 'json' } is the default response
. then ( ( res : FeatureCollectionResponse < GridSectionGeoJsonResponse > ) =>
console . log ( 'Grid Section' , res )
) ;
A caixa solicitada não deve exceder 4 km de canto a canto, ou um erro de badboundingboxtoobig será retornado. As latitudes devem ser> = -90 e <= 90, mas as longitudes podem envolver cerca de 180. Para especificar uma caixa delimitadora que atravessa o anti-meridiano, use longitude maior que 180.
import {
GridSectionClient ,
GridSectionOptions ,
FeatureCollectionResponse ,
GridSectionGeoJsonResponse ,
GridSectionJsonResponse ,
} from '../src' ;
const API_KEY = '<YOUR_API_KEY>' ;
const client : GridSectionClient = GridSectionClient . init ( API_KEY ) ;
const options : GridSectionOptions = {
boundingBox : {
southwest : { lat : 52.208867 , lng : 0.11754 } ,
northeast : { lat : 52.207988 , lng : 0.116126 } ,
} ,
} ;
// Search a string for any character sequences that could be three word addresses
client . findPossible3wa ( 'filled.count.soap' ) ; // returns ['filled.count.soap']
client . findPossible3wa (
'this string contains a three word address substring: filled.count.soap'
) ; // returns ['filled.count.soap']
client . findPossible3wa ( 'filled.count' ) ; // returns []
// Search a string for any character sequences that could be three word addresses
client . isPossible3wa ( 'filled.count.soap' ) ; // returns true
client . isPossible3wa (
'this string contains a three word address substring: filled.count.soap'
) ; // returns false
client . isPossible3wa ( 'filled.count' ) ; // returns false
// Search a string for any character sequences that could be three word addresses
client . isValid3wa ( 'filled.count.soap' ) ; // returns Promise<true>
client . isValid3wa (
'this string contains a three word address substring: filled.count.soap'
) ; // returns Promise<false>
client . isValid3wa ( 'filled.count.negative' ) ; // returns Promise<false>