Get current coordinates in init() function

I need to make an automatic receipt of weather at the current coordinates when the user enters the view (that is, the user opens the view and already sees the current weather at his current coordinates). I made getting the weather at the current coordinates when the user clicks on the button get weather. But I can’t do it in the init function.

In the view I have a component, which captures coordinates:
<capture-coordinates bind="report.location" show-if="false" />
But when I try to get report.location in the init function, then I get undefined.

Is there some way to get the coordinates and make a request for the weather without pressing a special button?

Thanks in advance!

You likely need to put your function that gets the current weather on a timeout. The coordinates are captured, but it is likely just taking a short time longer than it takes your code to call report.location to fire.

You can check to see that the report.location variable is being set without calling a subsequent function using the debug console. Here is a post about how you can access view variables.

Another option is to get the weather via a CloudCode task. Since CloudCode.callTask is a blocking call, this should solve any timing issues that you have. Here’s some example code for the CloudCode task:

export async function run(params) {
   var apikey = "yourkeyhere"

   var url = 'https://api.openweathermap.org/data/2.5/weather?appid=' + apikey + '&lat=' + params.lat + '&lon=' + params.lon + '&units=imperial';

   const response = await fetch(url, {
        "method": "GET",
   });

   const json = await response.json();
   console.log(json);

   // extract weather for debugging purposes
   const weather = json.weather[0].description;
   console.log('weather: ', weather);

   return json; //this result can then be used in the app view JS
}

Thank you for the answer.

Your solution assumes that coordinates will be passed to the CloudCode task. Do I understand correctly that you think that if we call the CloudCode in an init() function with a location variable (like view.location.latitude and view.location.longitute), then it will be able to get a real, non-empty value?

Actually you are correct - setTimeout or setInterval is the best current solution (wait until there is a location, don’t assume there will be one in a certain time).
Based on your feedback, we’ve included an on-change to the component in our product roadmap, which will make this easier going forward.

Cool! Such event listener will be very helpful.