I just started building the weather app and wrote the code to get latitude and longitude . But it always shows it as undefined . Here is the code -
var got_location = true;
var error_message = "";
$("div").html("Latitude : "+latitude+"<br>Longitude : "+longitude);
$("div").html("Error : "+error_message);
got_location = false;
error_message = "Geolocation is not supported by this browser."
latitude = position.coords.latitude;
longitude = position.coords.longitude;
got_location = false;
error_message = "User denied the request for Geolocation."
error_message = "Location information is unavailable."
error_message = "The request to get user location timed out."
error_message = "An unknown error occurred."
Link - https://codepen.io/kshitij1234/pen/zwmJaM
I am guessing that is because the if condition gets evaluated before the function execution stops but why does this happen? How can I correct this? Also it would be wonderful if you could share some of your experience regarding correct practices of using functions and (document).ready .
Thank you in advance!!
"[CodePen]: An infinite loop (or a loop taking too long) was detected, so we stopped its execution. Sorry!"
To make code more like in other synchronous languages async functions were invented.
In your code you block the execution of event callbacks with a while loop.
Here’s the version of your pen that uses async/await pattern:
I don’t know how to use await, I’ll research it after, but I used the callbacks to call other functions like writing to the document. Is this bad practice with the introduction of promises/await?
After researching, i don’t see how it’s useful in this example. Or for this project. Most of what needs to be done is procedural, unless the camper was drawing with JS.
navigator.geolocation.getCurrentPosition is an asynchronous function, which means its callback isn’t executed immediately. It is invoked after the main code executes (and after adequate event has been triggered) on a separate stack.
I am sorry . That was not the original code in codepen . I was trying to tweak the code a little to get it to work. I have reset it, please try again
Thank you!! I did not know about this .