What3words Rest API에 대한 요청을하기위한 JavaScript 라이브러리. 이제 브라우저 및 노드 기반 환경 모두에서 사용을 더 잘 지원합니다! REST API 사용 방법에 대한 자세한 내용은 What3words 공개 API 문서를 참조하십시오.
What3words JavaScript Wrapper는 다음에 대한 프로그래밍 방식 액세스를 제공합니다.
NPM :
npm install @what3words/api
방사:
yarn add @what3words/api
내장 된 전송을 사용하려면 피어 종속성을 설치해야합니다. 기본 전송에 대한 자세한 내용은 전송 섹션을 참조하십시오.
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
는 What3words API에 대한 요청을하는 데 사용할 수있는 API 클라이언트를 인스턴스화하는 빠르고 쉬운 방법을 제공합니다. 또한 What3words API 클라이언트에서 호스트 및 API 버전 및 API 키와 같은 API 구성을 설정하기위한 헬퍼 기능을 제공합니다.
이 라이브러리의 What3words API 클라이언트는 요청 옵션을 검증하고 API 엔드 포인트에 대한 요청/응답 및 오류를 처리하는 데 사용됩니다. 각 클라이언트는 추상적 인 ApiClient
클래스를 확장합니다.
각 요청마다 특정 클라이언트가 있으며 What3wordsService
와 독립적으로 사용할 수 있습니다. 클라이언트 동작을 확장하거나 코드를 최소화하거나보다 극단적으로 예를 들어 사용자 정의 전송을 사용하여 각 클라이언트에서 요청을 다르게 처리하려는 경우 특히 유용 할 수 있습니다.
모든 클라이언트는 다음 매개 변수를 수락합니다.
매개 변수 | 데이터 유형 | 기본값 |
---|---|---|
아파키 | 끈 | '' |
구성 | config.host | https://api.what3words.com |
config.apiversion | v3 |
전송은 API에 대한 요청을 실행하는 기능입니다. ClientRequest
주어지면 운송은 TransportResponse
로 해결되는 약속을 반환해야합니다.
ClientRequest
다음 속성으로 구성됩니다.
재산 | 데이터 유형 |
---|---|
주인 * | string |
URL * | string |
방법 * | get 거나 post |
질문 | object |
헤더 | object |
몸 | object |
형식 * | json 또는 geojson . 기본값 : json |
TransportResponse
는 다음 속성으로 구성됩니다.
재산 | 데이터 유형 |
---|---|
상태 * | number |
statustext * | string |
몸 * | any |
헤더 | object |
이 라이브러리에는 사용할 수있는 두 개의 내장 전송이 있습니다. 크로스 페치 또는 axios. What3wordsService
또는 클라이언트의 초기화시 사용하려는 전송을 지정하여 클라이언트를 직접 인스턴스화하려면.
사용 가능한 두 가지 내장 전송이 있습니다.
이 중 하나를 사용하려면 피어 종속성을 설치해야합니다. 기본적으로 크로스 페치는 What3wordsService
또는 재정의가 제공되지 않은 인스턴스화 클라이언트에 의해 가정됩니다.
NPM :
npm install cross-fetch
또는
npm install axios
방사:
yarn add cross-fetch
또는
yarn add axios
다른 통합이 있거나 이미 다른 곳에서 HTTP 라이브러리를 사용하는 경우 유용 할 수 있습니다.
그렇게하려면 자신의 Transport
정의하여 What3wordsService
또는 클라이언트로 전달하여 사용해야합니다.
당신이 만든 맞춤형 Transport
ClientRequest
인수로 받아들이고 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 )
) ;
요청 된 상자는 모퉁이에서 모퉁이에서 4km를 초과하지 않아야합니다. 위도는> = -90 및 <= 90이어야하지만, 경도는 180 정도를 감싸 수 있습니다. 반 머리 디안을 가로 지르는 경계 박스를 지정하려면 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>