Question

I'm experimentig with geolocation, but I'm having problems in accessing the information in the coords property of the getCurrentPosition method.

This is my current code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

  <script type="text/javascript" src="jLocation.js"></script>

  <title>Location Demo </title>   
</head>

<body>

<h1>Location Test File</h1>

<h2>Information</h2>
  <div id="g-information">
    <ul>
        <li>
           Your position is <span id="latitude" class="g-info">unavailable</span>° latitude,
           <span id="longitude" class="g-info">unavailable</span>° longitude (with an accuracy of
           <span id="position-accuracy" class="g-info">unavailable</span> meters)
        </li>
    </ul>
</div>

<script type="text/javascript">
window.onload = function (){
    document.getElementById('latitude').innerHTML = getLatitude();
}   

function getLatitude(){
    if (window.navigator && window.navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}

function showPosition(position){
    console.log(position.coords.latitude);
}
</script>

</body>

</html>

I'm not getting anything in the console.log from the showPosition method. Wasn't I supposed to get the latitude?

What am I doing wrong? Thanks in advance

Was it helpful?

Solution

Your code is the wrong way round. You can't do this for example:

document.getElementById('latitude').innerHTML = getLatitude();

You can't assign a function to the innerHTML of an element. (Note: you can assign the return from a function, but that's not what's happening here...)

Try this instead:

window.onload = getLatitude;

function getLatitude() {
  if (window.navigator && window.navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  }
}

function showPosition(position) {
  var latitude = position.coords.latitude;
  document.getElementById('latitude').innerHTML = latitude;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top