Skip to content

Commit

Permalink
adds server search functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
lishiyo committed Jan 27, 2015
1 parent 212b148 commit c0560fd
Show file tree
Hide file tree
Showing 16 changed files with 436 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Expand Up @@ -25,5 +25,5 @@ ENV NODE_ENV development

# Port 3000 for server
# Port 35729 for livereload
EXPOSE 3000 35729
EXPOSE 3000 4000
CMD ["grunt"]
86 changes: 86 additions & 0 deletions app/controllers/foursquare.server.controller.js
@@ -0,0 +1,86 @@
'use strict'

var http = require("http"),
async = require('async'),
search = require("./foursquare_search"),
getFoodPics = require("./foursquare_foodpics");

/** Main Search **/


function parseResults (req, parsedData) {

//items is an array of venues
var items = parsedData.response.groups[0].items;
var result = [];
var venueIds = [];

for (i = 0; i < items.length; i++) {
var venue = items[i].venue
var id = venue.id;
var name = venue.name;

// Foursquare already provides a formatted address and phone number for us
var location = venue.location;
var address = venue.location && venue.location.formattedAddress;
var contact = venue.contact && venue.contact.formattedPhone;
var stats = venue.stats;
var checkins = venue.hereNow;
// This will return null if venue.price is undefined
var price = venue.price && venue.price.tier;
var rating = venue.rating;
// Foursquare also gives us it's best guess if a venue is open
var hours = venue.hours && venue.hours.isOpen;
var url = venue.url;

result.push({
id: id,
name: name,
location: location,
address: address,
contact: contact,
stats: stats,
checkins: checkins,
price: price,
rating: rating,
open: hours,
url: url
});

venueIds.push(id);
}
return [result, venueIds];
};


exports.searchFood = function(req, res) {
var searchQuery = {
query: req.query.query,
lat: req.query.lat,
lng: req.query.lng
};

search(searchQuery, function(err, parsedData){
if (err) {
return console.error('There was an error: ' + err.message);
}
var results = parseResults(req, parsedData);
var result_list = results[0];
var venueIds = results[1];

// makes call to getAllFood
getFoodPics(venueIds, function(err, photoData){
console.log("getFoodPics called with photoData\n", photoData);

var allVenues = {
result_list: result_list,
photoObjs: photoData
}

res.json(allVenues);
});

});

};

7 changes: 7 additions & 0 deletions app/controllers/foursquare_config.js
@@ -0,0 +1,7 @@
//config.js

module.exports.foursquare = {
// Foursquare API keys in development
'clientId' : 'PJERQVMJ3DURUE5YKR50CSQGMYIPIBZQESKBK35SC1ZXQJ0R',
'clientSecret' : 'XKGURJJDVQT3TSARQJDUR1BGZ1YIKR2K5Z4GGQOJ5RCAXTM3'
}
64 changes: 64 additions & 0 deletions app/controllers/foursquare_foodpics.js
@@ -0,0 +1,64 @@
'use strict'

var async = require('async');
var http = require('http');
var https = require('https');
var secrets = require('./foursquare_config');
var foursquareClientId = process.env.FS_CLIENT_ID || secrets.foursquare.clientId;
var foursquareClientSecret = process.env.FS_CLIENT_SECRET || secrets.foursquare.clientSecret;
var photoObjs = [];

// get food pics for one venue
var getOneFood = function(vId, cb){
var options = {
host: 'api.foursquare.com',
port: 443,
path: '/v2/venues/' + vId + "/photos?limit=2&v=20150125&client_id=" + foursquareClientId + '&client_secret=' + foursquareClientSecret,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};

var req = https.get(options, function(res) {
var dataChunks = [];
res.on('data', function(chunk) {
dataChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(dataChunks);
var stringBody = body.toString('utf-8');
var parsedData = JSON.parse(stringBody);
var photoData = parsedData['response']['photos']['items'];
for (var i = 0; i < photoData.length ; i++) {
var obj = {
url: photoData[i]['prefix']+"300x300"+photoData[i]['suffix'],
venueId: vId
}
if (obj !== undefined) {
photoObjs.push(obj);
}
}
console.log("getOneFood for vId: ", vId);
cb(null);
});
});

req.on('error', function(error) {
cb(error);
});

req.end();
}

var getAllFood = function(venueIds, callback) {
async.each(venueIds, getOneFood, function(err) {
if( err ) {
console.log('getAllFood error', err);
} else {
console.log("finished async.each\n", photoObjs);
callback(null, photoObjs);
}
});
}

module.exports = getAllFood;
47 changes: 47 additions & 0 deletions app/controllers/foursquare_search.js
@@ -0,0 +1,47 @@
'use strict'

module.exports = function(query, callback) {
var http = require('http');
var https = require('https');
var secrets = require('./foursquare_config');
// We'll get our API keys from a config file if we can't find an 'FS_CLIENT_ID' environmental variable
var foursquareClientId = process.env.FS_CLIENT_ID || secrets.foursquare.clientId;
var foursquareClientSecret = process.env.FS_CLIENT_SECRET || secrets.foursquare.clientSecret;

var lat = query.lat,
lng = query.lng;

var options = {
host: 'api.foursquare.com',
port: 443,
// path: '/v2/venues/explore?client_id=' + foursquareClientId + '&client_secret=' + foursquareClientSecret + '&v=20140125&ll=40.72078,-74.001119&query=' + query,

path: '/v2/venues/explore?client_id=' + foursquareClientId + '&client_secret=' + foursquareClientSecret + '&v=20150125&ll=' + lat + "," + lng + '&query=' + query.query,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};

var req = https.request(options, function(res) {
var dataChunks = [];
res.on('data', function(chunk) {
dataChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(dataChunks);
var stringBody = body.toString('utf-8');
var parsedData = JSON.parse(stringBody);
// API call
console.log(options.host + options.path);

callback(null, parsedData);
});
});

req.end();

req.on('error', function(error) {
console.log('ERROR: ' + error.message);
});

}
2 changes: 1 addition & 1 deletion app/routes/articles.server.routes.js
Expand Up @@ -4,7 +4,7 @@
* Module dependencies.
*/
var users = require('../../app/controllers/users.server.controller'),
articles = require('../../app/controllers/articles.server.controller');
articles = require('../../app/controllers/articles.server.controller');

module.exports = function(app) {
// Article Routes
Expand Down
12 changes: 12 additions & 0 deletions app/routes/foursquare.server.routes.js
@@ -0,0 +1,12 @@
'use strict';

/**
* Module dependencies.
*/

module.exports = function(app) {
var foursquare = require('../../app/controllers/foursquare.server.controller');

// foursquare search Routes
app.route('/searchFood').get(foursquare.searchFood);
};
2 changes: 1 addition & 1 deletion app/views/layout.server.view.html
Expand Up @@ -63,7 +63,7 @@

{% if process.env.NODE_ENV === 'development' %}
<!--Livereload script rendered -->
<script type="text/javascript" src="http://{{request.hostname}}:35729/livereload.js"></script>
<script type="text/javascript" src="http://{{request.hostname}}:4000/livereload.js"></script>
{% endif %}

<!--[if lt IE 9]>
Expand Down
10 changes: 5 additions & 5 deletions gruntfile.js
Expand Up @@ -18,34 +18,34 @@ module.exports = function(grunt) {
serverViews: {
files: watchFiles.serverViews,
options: {
livereload: true
livereload: 4000
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint'],
options: {
livereload: true
livereload: 4000
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true
livereload: 4000
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint'],
options: {
livereload: true
livereload: 4000
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint'],
options: {
livereload: true
livereload: 4000
}
},
mochaTests: {
Expand Down
84 changes: 83 additions & 1 deletion public/modules/core/controllers/home.client.controller.js
@@ -1,9 +1,91 @@
'use strict';

var setUpMap = function(){
var getLocation = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}

var showPosition = function(position) {
var theLatLng = new google.maps.LatLng(Number(position.coords.latitude), Number(position.coords.longitude));
console.log("showposition", theLatLng);

document.getElementById('lat').setAttribute("value", position.coords.latitude);
document.getElementById('lng').setAttribute("value", position.coords.longitude);

var mapOptions = {
zoom: 15,
center: theLatLng
};

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

var centerMarker = new google.maps.Marker({
position: theLatLng,
map: map,
title: "Center",
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});

var infoWindows = [];
var markers = [];
var latLngBounds = new google.maps.LatLngBounds();

if (latLng) {
latLng.forEach(function(item){
infoWindows.push(new google.maps.InfoWindow({
content: "<div>" + item[2] + "</div>" + "<div>" + "Rating: " + item[3] + "</div>" +
"<div>" + "Price Level: " + item[4] + "</div>"
}));

var latLng = new google.maps.LatLng(item[0], item[1]);

markers.push(new google.maps.Marker({
position: latLng,
map: map,
title: item[2],
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
}));
latLngBounds.extend(latLng);
});
}

map.setCenter(latLngBounds.getCenter());
map.fitBounds(latLngBounds);

//console.log(infoWindows)
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function(innerKey) {
var clicks = 0;
return function() {
// console.log(infoWindows[i]);
clicks++;
infoWindows[innerKey].open(map, markers[innerKey]);
}
}(i));
}
}

getLocation();
}


angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
}

var loadScript = function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'callback=setUpMap';
document.body.appendChild(script);
}

loadScript();
}

]);

0 comments on commit c0560fd

Please sign in to comment.