Help needed on simple geolocation code

Help needed on simple geolocation code


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.


You have several errors in the console you need to address. One is being caused by reference a non-existent element:

  if (navigator.geolocation) {        
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";

You have not defined an element and assigned to the variable x, so x is undefined, so you can not set innerHTML of undefined.


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 =;
var 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.


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