I’ve tried several different ways of setting up my code so that I pull my longitude and latitude before I call a fetch command with no luck. I am trying to use vanilla js to complete the project. If anyone could tell me what I can do in order to:
Get Longitude and Latitude before calling fetch
I would be most grateful. Here is my latest version of code:
var arr = [];
var lon, lat;
start();
second(lon, lat);
function start(){
function success(pos){
lon = pos.coords.longitude;
lat = pos.coords.latitude;
};
function error(err){
alert(`There was a ${err} error`)
}
(navigator.geolocation.getCurrentPosition(success, error));
}
function second(a, b){
var url = `https://fcc-weather-api.glitch.me/api/current?lon=${a}&lat=${b}`;
fetch().then(function(response){
return response.json();
}).then(function(data){
for(x in data) {
return arr.push(data[x]);
};
})
}
I personally used this ip lookup service https://ipinfo.io/json
There are a few out there that do the same job.
Then pass the co-ords to your weather service.
No, but getting the longitude/latitude takes time, so you need to do everything you want to do afterwards in the callback (acquiring geolocation is an asynchronous operation).
My new code moved fetch to the callback. Thanks again. I was racking my brain for hours.
var arr = [];
var lon, lat;
start();
function start(){
function success(pos){
lon = pos.coords.longitude;
lat = pos.coords.latitude;
var url = `https://fcc-weather-api.glitch.me/api/current?lon=${lon}&lat=${lat}`;
fetch(url).then(function(response){
return response.json();
}).then(function(data){
for(x in data) {
arr.push(data);
};
})
};
function error(err){
alert(`There was a ${err} problem`)
}
(navigator.geolocation.getCurrentPosition(success, error));
}