0

I'm building a weather App using reactjs and the geolocation(navigator) api with the darksky weather api. I got the longitude and latitude displaying correctly, but when I try to retrieve the data I get a {code: 400, error: "The given location (or time) is invalid."}. However, if i manually put the address into the browser I get the proper JSON returned.

Example URL request: https://api.darksky.net/forecast/{api_secret_key}/37.4498,-77.3047

Looking at the headers in the console it doesn't even appear that the requested URL contains the longitude and latitude I'm passing in. Might it be that the weather API call is being executed before I get the latitude and longitude?

Request URL per console: https://api.darksky.net/forecast/{api_secret_key}/,

  getWeather = async (e) => { //Get weather data
    let latitude = '';
    let longitude = '';
    e.preventDefault(); //prevent page reload behaviour
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
        longitude = position.coords.longitude.toFixed(4);

        console.log("Latitude: " + latitude + ", Longitude: " + longitude);

      });
    } else {
      console.log("Geolocation not available");
    }

    //Pass the lattitude and longitude values from the location API call to the weather API
    const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/${latitude},${longitude}`);
    const weather_data = await weather_api_call.json(); //retrieve weather API data

    console.log(weather_data); //print weather API data to console
  }

Answer: Ended up moving the fetch and logging of the weather API data into the getCurrentPosition function

  getWeather = (e) => {
    e.preventDefault(); //prevent page reload behaviour

    if ("geolocation" in navigator) { //if the users allows geolocation to be active
      navigator.geolocation.getCurrentPosition(async (position) => {  //access naviagotr API & get the users current lat and lon

        let latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
        let longitude = position.coords.longitude.toFixed(4);

         console.log("Latitude: " + latitude + " Longitude: " + longitude); //check lat and lon 

          //Pass the lattitude and longitude values from the location API call to the weather API
          const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/`+latitude+`,`+longitude); //run API call after when lat and lon data is gotten
          const weather_data = await weather_api_call.json(); //retrieve weather API data after the call is executed with the lat and lon

          console.log(weather_data); //print weather API data to console

      });
    } else {
      console.log("Geolocation not available"); //Log if user blocks location in browser
  }
}
Red Rabbit
  • 115
  • 1
  • 11
  • it's not an exact duplicate, but it's the exact same problem. it's the most classic javascript callback / asynchronous error there is. your console log and `fetch` calls will execute before the callback function to `getCurrentPosition` – azium Nov 25 '18 at 01:12

1 Answers1

1

navigator.geolocation.getCurrentPosition is an async call where you're setting the values of latitude and longitude in the supplied callback. However the getWeather function just keeps executing along and calls the fetch with the original latitude and longitude values which are defined as empty strings.

If you move your fetch calls into the callback of navigator.geolocation.getCurrentPosition where you are sure that latitude and longitude are defined it should be fine.

Dennis Ruiter
  • 205
  • 3
  • 8
  • Thanks for the answer, it gave me enough information to know what was wrong, but didn't hold my hand in finding a fix – Red Rabbit Nov 25 '18 at 17:52