-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
70 lines (58 loc) · 2.37 KB
/
app.js
File metadata and controls
70 lines (58 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Import required packages
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const PORT = 3000;
// Configure Express
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
// Google Maps API key (replace with your own)
const GOOGLE_MAPS_API_KEY = 'AIzaSyAV9WZZSco82LmSOTD4CAgXFSahKfctzcg';
// Route: Home page
app.get('/', (req, res) => {
res.render('index');
});
// Route: Search for restaurants
app.post('/search', async (req, res) => {
const city = req.body.city;
const criterion = req.body.criterion;
try {
// Geocoding API to get city coordinates
const geoResponse = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json`, {
params: {
address: city,
key: GOOGLE_MAPS_API_KEY,
},
});
// Check if results exist
if (!geoResponse.data.results || geoResponse.data.results.length === 0) {
console.error('City not found!');
return res.status(404).send('City not found. Please try a different city.');
}
const location = geoResponse.data.results[0].geometry.location;
// Places API to find restaurants based on criteria
const placesResponse = await axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json`, {
params: {
location: `${location.lat},${location.lng}`,
radius: 5000, // Radius in meters
type: 'restaurant',
keyword: criterion,
key: GOOGLE_MAPS_API_KEY,
},
});
const restaurants = placesResponse.data.results;
if (!restaurants || restaurants.length === 0) {
return res.status(404).send(`No restaurants found for "${criterion}" in ${city}.`);
}
res.render('results', { city, criterion, restaurants });
} catch (error) {
console.error('Error fetching data from Google API:', error.response?.data || error.message);
res.status(500).send('An error occurred while processing your request.');
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});