Skip to content
This repository has been archived by the owner on Nov 29, 2023. It is now read-only.

changed: added geocoding api #243

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions app/controllers/api-v2-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const utils = require( '../lib/utils' );
const keys = require( '../lib/router-utils' ).idEncryptionKeys;
const router = express.Router();
const quotaErrorMessage = 'Forbidden. No quota left';
const configModel = require( '../models/config-model' );
const getMapboxResponse = require( '../lib/geocoder/mapbox' );
// var debug = require( 'debug' )( 'api-controller-v2' );

module.exports = app => {
Expand All @@ -27,6 +29,9 @@ router
} )
.get( '/version', getVersion )
.post( '/version', getVersion )

.get( '/geocoder', getGeocodeResponse )

.all( '*', authCheck )
.all( '*', _setQuotaUsed )
.all( '*', _setDefaultsQueryParam )
Expand Down Expand Up @@ -427,6 +432,17 @@ function removeInstance( req, res, next ) {
.catch( next );
}

function getGeocodeResponse( req, res ){
switch( configModel.server.geocoder.provider ){
case 'mapbox':
getMapboxResponse( req.query, ( response ) => {
res.json( response );
} );
break;
default:
throw new Error( 'Geocoder provider is not configured. Please configure `config.geocoder.provider`' );
}
}

/**
* @param {module:api-controller~ExpressRequest} req - HTTP request
Expand Down
47 changes: 47 additions & 0 deletions app/lib/geocoder/mapbox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const configModel = require( '../../models/config-model' );
const request = require( 'request' );

module.exports = function getMapboxResponse( query, callback ) {

const config = configModel.server.geocoder;
let url = config.url || 'https://api.mapbox.com/geocoding/v5/mapbox.places/{address}.json';
const accessToken = config.apiKey;

const params = Object.assign( {}, config.params, {
access_token: accessToken,
proximity: query.$center, // -93.17284130807734,45.070291367515466
bbox: query.$bbox, // -93.13644718051957,45.05118347242032,-93.17284130807734,45.070291367515466
limit: query.$limit,
} );

return request( url.replace( '{address}', query.address ),
{
qs: params
},
( error, response, body ) => {
let data;
try {
data = JSON.parse( body );
} catch( e ) {
data = {
features: [],
};
}
data = data.features ?
data.features.map( f => {
return {
geometry: f.geometry,
id: f.id,
type: f.type,
properties: {
name: f.place_name,
type: f.place_type.join( ',' ),
score: f.relevance,
accuracy: f.properties.accuracy,
}
};
} ) : { error: data.message };
callback( data );
}
);
};