Une bibliothèque JavaScript pour faire des demandes à l'API What3Words REST. Maintenant, avec une meilleure prise en charge pour une utilisation dans les environnements basés sur le navigateur et les nœuds! Voir la documentation API publique What3Words pour plus d'informations sur la façon d'utiliser notre API REST.
L'écran JavaScript What3words vous donne un accès programmatique:
NPM:
npm install @what3words/api
fil:
yarn add @what3words/api
Si vous souhaitez utiliser les transports intégrés, vous devrez également installer les dépendances par les pairs pour eux. Pour plus d'informations sur les transports par défaut, lisez la section sur les transports.
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...
Le What3wordsService
fournit un moyen rapide et facile d'instancier les clients API qui peuvent être utilisés pour faire des demandes par rapport à l'API What3Words. Il fournit également des fonctions d'assistance pour définir la configuration de l'API, telles que la version hôte et API et votre clé API sur les clients API What3Words.
Les clients API What3Words de cette bibliothèque sont utilisés pour valider les options de demande, sérialiser et gérer la demande / réponse et les erreurs par rapport à un point de terminaison de l'API. Chaque client étend la classe abstraite ApiClient
.
Il existe un client spécifique pour chaque demande et vous pouvez les utiliser indépendamment du What3wordsService
. Cela peut être particulièrement utile si vous souhaitez étendre le comportement du client, minimiser votre code ou, dans un exemple plus extrême, utiliser un transport personnalisé pour gérer les demandes différemment dans chaque client.
Chaque client accepte les paramètres suivants:
Paramètre | Type de données | Valeur par défaut |
---|---|---|
apikey | chaîne | '' |
configurer | config.host | https://api.what3words.com |
config.apiversion | v3 |
Le transport est une fonction responsable de l'exécution de la demande contre l'API. Compte tenu d'un ClientRequest
le transport devrait renvoyer une promesse qui se résout à TransportResponse
.
Un ClientRequest
se compose des propriétés suivantes:
Propriété | Type de données |
---|---|
hôte * | string |
URL * | string |
méthode * | get ou post |
requête | object |
têtes | object |
corps | object |
format * | json ou geojson . Par défaut: json |
Une TransportResponse
se compose des propriétés suivantes:
Propriété | Type de données |
---|---|
statut * | number |
StateStext * | string |
corps * | any |
têtes | object |
Il existe deux transports intégrés disponibles avec cette bibliothèque que vous pouvez utiliser; Soit le crossoch, soit Axios. En spécifiant quel transport vous souhaitez utiliser lors de l'initialisation du What3wordsService
ou d'un client, si vous souhaitez instancier un client pour vous-même.
Il y a deux transports intégrés disponibles:
Afin d'utiliser l'un ou l'autre de ces éléments, vous aurez besoin d'installer la dépendance des pairs. Par défaut, le crossoch est supposé par le What3wordsService
ou tout client instancié où aucune remplacement n'est fournie.
NPM:
npm install cross-fetch
ou
npm install axios
fil:
yarn add cross-fetch
ou
yarn add axios
Vous pouvez fournir votre propre transport personnalisé, si vous souhaitez utiliser une autre bibliothèque pour gérer les demandes, ce qui pourrait être utile si vous avez d'autres intégrations ou si vous utilisez déjà une bibliothèque HTTP ailleurs.
Pour ce faire, vous devez définir votre propre Transport
et le transmettre dans What3wordsService
ou Client pour l'utiliser.
Le Transport
personnalisé que vous créez devrait être une fonction qui accepte un ClientRequest
comme argument et renvoie une promesse qui se résout en une 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 )
) ;
La boîte demandée ne doit pas dépasser 4 km de coin à l'angle, ou une erreur Badboundingboxtoobig sera renvoyée. Les latitudes doivent être> = -90 et <= 90, mais les longitudes sont autorisées à s'enrouler autour de 180. Pour spécifier une boîte de délimitation qui traverse l'antiridien, utilisez une longitude supérieure à 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>