Eine JavaScript -Bibliothek, um Anfragen an die What3Words -REST -API zu stellen. Mit besserer Unterstützung für den Einsatz in Browser- und Knotenbasis -Umgebungen! Weitere Informationen zur Verwendung unserer REST -API finden Sie in der öffentlichen API -Dokumentation von What3words.
Mit dem JavaScript -Wrapper von What3Words können Sie programmatischer Zugriff auf:
NPM:
npm install @what3words/api
Garn:
yarn add @what3words/api
Wenn Sie die eingebauten Transporte verwenden möchten, müssen Sie auch die Peer-Abhängigkeiten für sie installieren. Weitere Informationen zu den Standardtransports finden Sie im Abschnitt über Transporte.
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...
Der What3wordsService
bietet eine schnelle und einfache Möglichkeit, die API -Clients zu instanziieren, mit denen Anforderungen an die What3Words -API gestellt werden können. Es bietet auch Helferfunktionen für die Einstellung der API -Konfiguration, z. B. die Host- und API -Version und Ihren API -Schlüssel über die What3Words -API -Clients.
Die API -Clients von What3Words in dieser Bibliothek werden verwendet, um Anforderungsoptionen zu validieren, Anforderungen/Antwort und Fehler gegen einen API -Endpunkt zu serialisieren und zu behandeln. Jeder Client erweitert die abstrakte ApiClient
-Klasse.
Für jede Anfrage gibt es einen bestimmten Kunden und Sie können sie unabhängig vom What3wordsService
verwenden. Dies kann besonders nützlich sein, wenn Sie das Kundenverhalten erweitern, Ihren Code minimieren oder in einem extremeren Beispiel einen benutzerdefinierten Transport verwenden möchten, um Anforderungen in jedem Kunden unterschiedlich zu bearbeiten.
Jeder Client akzeptiert die folgenden Parameter:
Parameter | Datentyp | Standardwert |
---|---|---|
Apikey | Saite | '' |
Konfiguration | config.host | https://api.what3words.com |
config.apiversion | v3 |
Der Transport ist eine Funktion, die für die Ausführung der Anfrage gegen die API verantwortlich ist. Angesichts eines ClientRequest
sollte der Transport ein Versprechen zurückgeben, das sich zur TransportResponse
entschlossen.
Eine ClientRequest
besteht aus den folgenden Eigenschaften:
Eigentum | Datentyp |
---|---|
Gastgeber * | string |
URL * | string |
Methode * | get oder post |
Abfrage | object |
Header | object |
Körper | object |
Format * | json oder geojson . Standard: json |
Eine TransportResponse
besteht aus den folgenden Eigenschaften:
Eigentum | Datentyp |
---|---|
Status * | number |
StatuStext * | string |
Körper * | any |
Header | object |
Mit dieser Bibliothek stehen zwei eingebaute Transporte zur Verfügung, die Sie verwenden können. entweder Kreuzfassungen oder Axios. Indem Sie angeben, welcher Transport Sie bei der Initialisierung des What3wordsService
oder eines Kunden verwenden möchten, wenn Sie einen Kunden für sich selbst instanziieren möchten.
Es stehen zwei eingebaute Transporte zur Verfügung:
Um eines dieser diese zu verwenden, müssen Sie die Peer -Abhängigkeit installieren. Standardmäßig wird die Querabnahme durch den What3wordsService
oder einen sofortigen Client angenommen, bei dem keine Überschreibung bereitgestellt wird.
NPM:
npm install cross-fetch
oder
npm install axios
Garn:
yarn add cross-fetch
oder
yarn add axios
Sie können Ihren eigenen benutzerdefinierten Transport bereitstellen, wenn Sie eine andere Bibliothek für die Bearbeitung von Anfragen verwenden möchten. Dies kann nützlich sein, wenn Sie andere Integrationen haben oder bereits eine HTTP -Bibliothek an anderer Stelle verwenden.
Dazu müssen Sie Ihren eigenen Transport
definieren und in den What3wordsService
oder Client übergeben, um ihn zu verwenden.
Der benutzerdefinierte Transport
den Sie erstellen, sollte eine Funktion sein, die eine ClientRequest
als Argument akzeptiert und ein Versprechen zurückgibt, das sich auf eine TransportResponse
entscheidet.
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 )
) ;
Das angeforderte Box darf 4 km von Ecke zu Ecke nicht überschreiten, und ein badboundingboxoBig -Fehler wird zurückgegeben. Die Breiten müssen> = -90 und <= 90 sein, aber Längswerte dürfen etwa 180 einwickeln. Um eine Begrenzungsbox anzugeben, die den Anti-Meridian überschreitet, verwenden Sie Längengrade von mehr als 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>