Una biblioteca de JavaScript para hacer solicitudes a la API REST What3words. ¡Ahora con un mejor soporte para su uso tanto en entornos de navegador como de nodo! Consulte la documentación de la API pública What3Words para obtener más información sobre cómo usar nuestra API REST.
What3words JavaScript Wrapper le brinda acceso programático a:
NPM:
npm install @what3words/api
hilo:
yarn add @what3words/api
Si desea utilizar los transportes incorporados, también deberá instalar las dependencias de pares para ellos. Para obtener más información sobre los transportes predeterminados, lea la sección 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...
What3wordsService
proporciona una manera rápida y fácil de instanciar a los clientes API que pueden usarse para realizar solicitudes contra la API What3Words. También proporciona funciones auxiliares para configurar la configuración de API, como la versión host y API y su clave API en los clientes API What3words.
Los clientes API What3Words en esta biblioteca se utilizan para validar las opciones de solicitud, serializar y manejar la solicitud/respuesta y los errores contra un punto final API. Cada cliente extiende la clase abstracta ApiClient
.
Hay un cliente específico para cada solicitud y puede usarlos independientemente de What3wordsService
. Esto puede ser particularmente útil si desea extender el comportamiento del cliente, minimizar su código o, en un ejemplo más extremo, usar un transporte personalizado para manejar las solicitudes de manera diferente en cada cliente.
Cada cliente acepta los siguientes parámetros:
Parámetro | Tipo de datos | Valor predeterminado |
---|---|---|
apagado | cadena | '' |
configuración | config.host | https://api.what3words.com |
config.apiversión | v3 |
El transporte es una función responsable de ejecutar la solicitud contra la API. Dada una ClientRequest
el transporte debe devolver una promesa que resuelva TransportResponse
.
Una ClientRequest
consta de las siguientes propiedades:
Propiedad | Tipo de datos |
---|---|
anfitrión * | string |
URL * | string |
método * | get o post |
consulta | object |
encabezado | object |
cuerpo | object |
formato * | json o geojson . Valor predeterminado: json |
Una TransportResponse
consiste en las siguientes propiedades:
Propiedad | Tipo de datos |
---|---|
estado * | number |
StatusText * | string |
cuerpo * | any |
encabezado | object |
Hay dos transportes incorporados disponibles con esta biblioteca que puede usar; Fetch o Axios. Al especificar qué transporte le gustaría usar en la inicialización del What3wordsService
o un cliente, si desea instanciar a un cliente para usted.
Hay dos transportes incorporados disponibles:
Para usar cualquiera de estos, necesitará instalar la dependencia de los pares. Por defecto, se supone que What3wordsService
o cualquier cliente instanciado donde no se proporciona anulación.
NPM:
npm install cross-fetch
o
npm install axios
hilo:
yarn add cross-fetch
o
yarn add axios
Puede proporcionar su propio transporte personalizado, si desea utilizar otra biblioteca para manejar solicitudes, lo que podría ser útil si tiene otras integraciones o si ya está utilizando una biblioteca HTTP en otro lugar.
Para hacerlo, debe definir su propio Transport
y transmitirlo a What3wordsService
o cliente para usarlo.
El Transport
personalizado que crea debe ser una función que acepte una ClientRequest
como argumento y devuelve una promesa que resuelve una 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 )
) ;
El cuadro solicitado no debe exceder los 4 km desde la esquina hasta la esquina, o se devolverá un error BadBoundingBextoobig. Las latitudes deben ser> = -90 y <= 90, pero las longitudes pueden envolver alrededor de 180. Para especificar una caja delimitadora que cruza el antimeridiano, use una longitud superior a 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>