Библиотека JavaScript, чтобы сделать запросы в API What3words Rest. Теперь с лучшей поддержкой для использования в средах как браузера, так и на основе узлов! Смотрите документацию What3Words Public API для получения дополнительной информации о том, как использовать наш API REST.
Обертка JavaScript What3Words дает вам программный доступ к:
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
обеспечивает быстрый и простой способ создания клиентов API, которые можно использовать для выполнения запросов против API What3words. Он также предоставляет вспомогательные функции для настройки конфигурации API, таких как версия Host и API и ваш ключ API для клиентов API What3words.
Клиенты API What3Words в этой библиотеке используются для проверки параметров запросов, сериализации и обработки запроса/ответа и ошибок по конечной точке API. Каждый клиент расширяет абстрактный класс ApiClient
.
Для каждого запроса есть конкретный клиент, и вы можете использовать его независимо от What3wordsService
. Это может быть особенно полезно, если вы хотите расширить поведение клиента, минимизировать свой код или, в более экстремальном примере, используйте пользовательский транспорт для по -разному обработки запросов у каждого клиента.
Каждый клиент принимает следующие параметры:
Параметр | DataType | Значение по умолчанию |
---|---|---|
apikey | нить | '' |
конфигурация | config.host | https://api.what3words.com |
config.apiversion | v3 |
Транспорт является функцией, ответственной за выполнение запроса против API. Учитывая ClientRequest
транспорт должен вернуть обещание, которое разрешается в TransportResponse
.
ClientRequest
состоит из следующих свойств:
Свойство | DataType |
---|---|
хозяин * | string |
URL * | string |
Метод * | get или post |
запрос | object |
заголовки | object |
тело | object |
формат * | json или geojson . По умолчанию: json |
TransportResponse
состоит из следующих свойств:
Свойство | DataType |
---|---|
статус * | number |
statustext * | string |
тело * | any |
заголовки | object |
В этой библиотеке доступно два встроенных транспорта, которые вы можете использовать; либо перекрестная, или аксиос. Указав, какой транспорт вы хотели бы использовать при инициализации 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 )
) ;
Запрашиваемая коробка не должна превышать 4 км от углового до угла, или будет возвращена ошибка Badboundingboxtoobig. Широты должны быть> = -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>