alert and function call within function happening out of order

I am making a pen that uses the navigator.geolocation function to get the longitude and latitude of the user. That much is working fine.

My issue is when I call the getWeatherInfo() function. You will see that the first line in that function calls another function getLocation(), then raises an alert - alert(location) in this case. However, I don't understand why that alert is raised before the function call to getLocation() takes place, since var location = getLocation(); function is called before alert(location)? I believe this is the case since there is an alert(lat + " " + lon);' in thegetLocation()` function and that alert comes up second.

So, not sure what is going on there.. This is probably related to why I am not getting back a result into var location = getLocation(); which shows up as undefined ???

Link to my pen

Here is the code also:

HTML:

<div id="data">
</div>

<button onclick="getWeatherInfo()">Click Me</button>

CSS:

#data {
  width: 500px;
  height: 200px;
  margin: 0 auto;
  background: purple;
  color: white;
  text-align: center;
}

Javascript:

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var lat = (Math.round(position.coords.latitude)).toString();
      var lon = (Math.round(position.coords.longitude)).toString();
      alert(lat + " " + lon); 
      return [lat, lon];
    });
  } else {
    alert("You must allow geolocation to retrieve weather data for your area");
  }
}

function getWeatherInfo() {
  var location = getLocation();
  alert(location); 
  $("#data").html(location[0] + " " + location[1]);
}

Note that jQuery is enabled and used in this pen.

Answers 1

  • It seems to grab the data but I see what you mean by calling out of order.. Try putting this line right by your alert within the function..

    $("#data").html(location[0] + " " + location[1]);
    

    That's probably not how you want to arrange you code though is it.. You'll have to set it up something like so:

    function getLocation(callback) {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var lat = (Math.round(position.coords.latitude)).toString();
          var lon = (Math.round(position.coords.longitude)).toString();
          //alert(lat + " " + lon); 
          var coords = [lat, lon];
          callback(coords);
          //return coords;
        });
      } else {
        alert("You must allow geolocation to retrieve weather data for your area");
      }
    }
    
    function getWeatherInfo() {
        getLocation(function(location){
            //alert(location); 
            $("#data").html(location[0] + " " + location[1]);
        });
    }
    

Related Articles