1

I'm trying to get coords through html's geolocation automatically on page load, but it isn't working.

 <body >
    <p id="demo">hi</p>

 </body>

 <script>

$(document).ready(function () {
    var x = document.getElementById("demo");
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
});
</script>

Any help is much appreciated.

https://jsfiddle.net/bushido/dozay2mo/

1
  • Check the answer (and the notes, they are important!) Commented Dec 5, 2016 at 0:37

1 Answer 1

1

You had a syntax error.

This is the fix:

var x;
$(document).ready(function () {
  x = document.getElementById("demo");
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
});
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="demo">hi</p>

Notes:
1. You need to make sure you load the jQuery library.
2. The getCurrentPosition on modern browsers require you to use SSL (https://), so if your website don't have SSL it will not work.
3. The x variable was a local variable (therefor was available only inside the ready block, and not inside the showPosition function.

Sign up to request clarification or add additional context in comments.

2 Comments

So I did have a syntax error and after i fixed that (thanks to you), the permission prompt comes up, but it still isn't putting the coordinates into the container. Edit: Browser has SSL (Firefox latest), works when I use $(document).on(click....
thanks so much friend, I should have seen that x was only defined locally and that's why it couldn't be accessed. Edit: of course it's the least I can do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.