Good day all, pardon my question logic as I am new here. I am building my first fullstack App using React and Node.I am thinking of three approaches but not sure what will work best.
APPROACH ONE
I want to be able to get user lat/long when they fill a form in the frontend and request access to their geolocation through the geolocation API. For example, when a user submit their region and community name, the backend will call the getCurrentPosition geolocation API. Then the returned lat/long will form part of the data to be sent to the database as shown in the extracted code below. But when I tried this approach, I ran into two challenges. First, an error message that navigator is not defined
. Second, I don't know how to retrieved the lat/long returned and declare it as a const to use it in creating the location. See the code below:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert("Your browser is out of fashion. There is no geo location!")
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude
console.log(`Your latitude is ${latitude} and your longitude is ${longitude}`)
return (latitude, longitude);
}
function error() {
alert("Can't detect your location. Try again later.")
}
How do I declare the lat/long as a const outside the function. Some like:
const communityName = req.body.communityName;
const latitude = (success).latitude;
const longitude = (success).longitude;
APPROACH 2
I downloaded the geolocation npm package and use it as in code below but get the error that navigator is not defined. If I am to use this approach, how can I define navigator and how can I get to declare the lat/long as a const outside of the function?
const geolocation = require('geolocation');
geolocation.getCurrentPosition(function (err, position) {
if (err) throw err
console.log(position)
})
APPROACH 3
I read about this approach but can't get a working example. It is suggested that I should use the geolocation API to get the user device lat/long and send the coords as part of req.body data to the backend API. If this is a good approach, is there a tutorial I can follow?
Please I am new to Javascript and coding but I have made serious progress but this as got me stocked on my project. No answer is too wrong lease. There is sense in nonsense.