I’m creating a simple weather scraper however am unable to get the browser to request permission to access a user’s location.
JS is:
require('dotenv').config();
const apiKey = process.env.API_KEY;
// onload event listener for api:
window.addEventListener('load', () => {
let lon;
let lat;
// asks permission to access users location:
navigator.permissions.request({ name: 'geolocation' })
.then((permission) => {
if (permission.state === 'granted'){
navigator.geolocation.getCurrentPosition((position) => {
try {
let lon = position.coords.longitude;
let lat = position.coords.latitude;
const locationData = `https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={apiKey}`;
fetch(locationData).then((response) => {
return response.json();
})
.catch((error) => {
console.error(error);
});
} catch (error) {
console.error(error);
}
});
}
});
});
I’ve tried the below but still no luck:
* Re-opened live server in Safari but Safari doesnt ask for permission to access location either.
* Confirmed Chrome & Safari had permission to access my location on my Mac.
* Realised I hadn't correctly used string interpolation for the locationData URL; so corrected URL.
* Code wrapped in try-catch.
* Created new API key.
* Added "navigator.permissions.request" but still no luck