0

I created a function to store latitude and longitude into global variables, so that I could pass them as parameters in another function, but I failed to make it work. I fixed the issue by putting my one function into the other, but am confused to as to why my original way didn't work?

The code below is from when the values being passed into the getWeather function, were not the values that should have been stored in the global variables, by the getCordinates function.

---Main app stars here---

console.log("Server starting")

const yargs = require("yargs");
const geocode = require("./geocode/geocode");
const weather = require("./weather/weather");
const request = require('request');
let cordinates = {
    lat: 0,
    lng: 0
}

const argv = yargs.options({
    a:{
        demand: true,
        alias: 'address',
        describe: 'Address to fetch weather for',
        string: true
    }
}).help().alias('help', 'h').argv;

geocode.getCordinates(argv.a, (errorMessage, results) => {
    if(errorMessage){
        console.log(errorMessage);
        console.log(results)
    }else{
        console.log(`${results.address} - ${results.city} ${results.state}, ${results.country}`)



    }

});

    weather.getWeather(cordinates.lat, cordinates.lng, (errorMessage, weatherResults) => {
                if(errorMessage){
                    console.log(errorMessage);
                    console.log(results);

                }   else {
                        console.log(`The current temperature is ${weatherResults.temp} degrees celcius, and it feels like ${weatherResults.feelsLike}.`)

        }
    });

---main app ends here ---

---getCordinates function starts here---

var getCordinates = (address, callback) =>{

    request({
    url: `http://www.mapquestapi.com/geocoding/v1/address?key=Dfgu2XcWvcvlYAbkz3B8gXr2z6SfTKtO&location=${encodeURIComponent(address)}`,
    json: true
}, (error, response, body) => {
    if(error){
        callback("Unable to connect to mapquest servers.", "Jack make big fart will be passed to the callback function as the results parameter.")      
    }else if(body.info.statuscode !== 0 && body.info.statuscode !== 200){
        callback("This location does not exist, please try again");
    } else{
        callback(undefined, {
            address: body.results[0].providedLocation.location.toUpperCase(),
            city:body.results[0].locations[0].adminArea5,
            state:body.results[0].locations[0].adminArea3,
            country:body.results[0].locations[0].adminArea1,
            lat:body.results[0].locations[0].latLng.lat,
            long:body.results[0].locations[0].latLng.lng
        });
    }   
});


}

---getCordinates function ends here---

---getWeather function starts here---

let tempConverter = (farenheit) => {
    return Math.round((farenheit - 32) * 5 / 9)
};


let getWeather = (latitude, longitude, callback) =>{

request({
    url:`https://api.darksky.net/forecast/d32506e0e791e1ea3d7f55f24f43b2ba/${latitude},${longitude}`, 
    json:true
}, (error, response, body) => {
    if(error){
        callback("Unable to connect to forecast.io servers.", error)
    }else if(response.statusCode === 400){
        callback(body.error)

    }else if(response.statusCode === 403){
        callback(response.statusCode, response.statusMessage)
    }else {
        callback(undefined, {
            temp: tempConverter(body.currently.temperature),
            feelsLike: tempConverter(body.currently.apparentTemperature)

        });
    }
});


};

EDIT: I added the other pieces of code. Sorry I didnt add it before!

noobcoderiam
  • 488
  • 4
  • 19
  • 1
    You don't show any code that ever puts any non-zero value into `cordinates.lat` or `cordinates.lng`. Not much we can do without seeing the code that assigns those properties. Best guess here is that you have a timing issue with asynchronous calls, but would need to see the code to know for sure. – jfriend00 Oct 26 '18 at 18:36
  • I reedited my question with the other code @jfriend00. I am reading into the page you linked Patrick Roberts. – noobcoderiam Oct 26 '18 at 18:44
  • You still don't show any code that assigns `cordinates.lat` or `cordinates.lng`, but it does appear it's likely a dup. – jfriend00 Oct 26 '18 at 18:47
  • Also, not related to your issue, but `cordinates` is not a global. It's a module level variable. – jfriend00 Oct 26 '18 at 18:48
  • @jfriend00, thank you for that tip! Also, I believe my problem was that because nodejs is asynchronous, both calls are made at the same time meaning the parameters passed in are always the original value? – noobcoderiam Oct 26 '18 at 21:20

0 Answers0