From 83be006a83c4d9c1f41d341b33e17190f2a62629 Mon Sep 17 00:00:00 2001 From: Joaquin Date: Tue, 6 May 2025 13:38:00 -0700 Subject: [PATCH] feature/geolocation implemented --- app.js | 10 ++++++++++ src/public/scripts/geolocation.js | 24 ++++++++++++++++++++++++ src/views/landing.ejs | 5 +++++ 3 files changed, 39 insertions(+) create mode 100644 src/public/scripts/geolocation.js diff --git a/app.js b/app.js index 6321d6e..9e5e519 100644 --- a/app.js +++ b/app.js @@ -28,6 +28,7 @@ app.set('views',path.join(__dirname, 'src/views')); app.use(express.urlencoded({ extended: true })); app.use("/static", express.static("./src/public")); app.use("/images", express.static("./src/public/images")); +app.use(express.json()); /*** Database ***/ const { connectMongo, getCollection } = require("./src/database/connection"); @@ -69,6 +70,15 @@ app.get('/aboutUs', (req, res) => { return res.status(status.Ok); }); +app.post('/api/location', async (req,res) => { + const { latitude, longitude } = req.body; + + const response = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&result_type=country&key=${process.env.geolocation_api}`); + + const data = await response.json(); + + res.json(data); +}); // Initialize database and start app initDatabase().then(() => { diff --git a/src/public/scripts/geolocation.js b/src/public/scripts/geolocation.js new file mode 100644 index 0000000..ebe001b --- /dev/null +++ b/src/public/scripts/geolocation.js @@ -0,0 +1,24 @@ +function getLocation() { + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition(success, error); + } +} + +function success(position) { + const { latitude, longitude } = position.coords; + + fetch("api/location" , { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ latitude, longitude }) + }).then(res => res.json()) + .then(data => { + console.log(data.results[0].formatted_address); + }) +} + +function error(err) { + console.error("Geolocation error: ", err); +} diff --git a/src/views/landing.ejs b/src/views/landing.ejs index d7a24d1..9b2c7c7 100644 --- a/src/views/landing.ejs +++ b/src/views/landing.ejs @@ -18,7 +18,12 @@ + + + + + <%- include("./partials/footer") %>