restaurants
Version:
Search a service and get a list of restaurants.
73 lines (58 loc) • 1.34 kB
JavaScript
/**
* Dependencies
*/
var findAll = require('./find-all')
, get = require('superagent').get;
/**
* Google Constants
*/
var ENDPOINT = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
, KEY = process.env.GOOGLE_API_KEY
, MAX_LIMIT = 20
, MAX_OFFSET = 40;
/**
* Expose search function
*/
module.exports = function(lat, lng, radius, all, callback) {
if (!KEY) throw new Error('Environment variable GOOGLE_API_KEY must be set.');
var query = {
key: KEY
, location: lat + ',' + lng
, radius: radius
, sensor: false
, types: 'restaurant'
};
if (all) {
findAll(query, MAX_LIMIT, MAX_OFFSET, getRestaurants, callback);
} else {
getRestaurants(query, 10, 0, callback);
}
};
/**
* Save the next page token for paging
*/
var next_page_token = null
, more_pages = true;
/**
* Get the restaurants
*/
function getRestaurants(query, limit, offset, callback) {
if (next_page_token) {
query.pagetoken = next_page_token;
}
if (query.pagetoken && !next_page_token) {
return callback(null, []);
}
setTimeout(function() {
get(ENDPOINT)
.query(query)
.end(function(err, res) {
if (err) {
callback(err);
} else {
next_page_token = res.body.next_page_token;
callback(err, res.body.results);
}
});
}, 2000);
}