Help needed on simple geolocation code

Hi!
I am trying to get getLocation function to work as in w3schools example, but something is obviously wrong with my code.
Here is my code:


Codepen is on https, it asks me to allow location access, but it does not display it.

what @rmdawson71 said +

The first place to look at is always your console, you have 3 errors on there but what is causing you problems is the 3rd one:

Uncaught ReferenceError: position is not defined
    at pen.js:4

the reason? you have variables declared at the top of your script that reference unknown variables ,

var lat = position.coords.latitude;
var long = position.coords.longitude;
var city = data.city;
var country = data.country;
var wheather = data.weatherType;

the machine does not know what ‘position’ and ‘data’ are. Take those declarations out and it will get your position, however it still will not be able to display it on your page as you requested because this:

var x = document.getElementById("#myp");

will return a null value for x, because that particular assignment is done before the page has loaded and so it doesn’t (yet) know what or where <div id="myp"/> is. To solve this , read up on jquery’s $( document ).ready() or the vanilla JS variation thereof, or just learn where to place the script so that it executes after the document has loaded.

2 Likes

Thank you, I managed to solve the problem and clarify the misunderstandings about JS I had.