0

I am trying to make a weather showing app using javascript from FCC project. In order to display the current weather first I have to find the location of the device. this works fine using HTML geolocation.But The latitude and longitude is giving me undefined error when i try to use it outside the function eventhough I am trying to assign it to a global variable.

$(document).ready(function(){
      var lon;
      var lat;
      function getLocation(){
        if(navigator.geolocation){
          navigator.geolocation.getCurrentPosition(showPosition);
      }
        else{
          console.log("your device is not suported!");
      }}

      function showPosition(position){
        var pos = position.coords
        lat = pos.latitude;
        lon = pos.longitude;

      }
      console.log(lat); // for debugging, here  is the undefined error
      $.ajax({
        type: 'GET',
        url: 'https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139',
        success: function(data){
          $('h1').html( "<strong>" + data.coord.lat + "</strong>" );
          console.log(latitude);
        },
        error: function(error){
          console.log(error);
        }

        });
      });

Thank you for the help :)

Nejweti
  • 113
  • 2
  • 11
  • You have an undefined "latitude" in your code. See the `console.log(latitude);` in your success function for the Ajax. Maybe change that to `data.coord.lat` (like the line above). – JonahAaron Sep 28 '17 at 20:30
  • check this: https://stackoverflow.com/questions/9935059/saving-variables-outside-of-navigator-geolocation-getcurrentposition-javascrip – ErisoHV Sep 28 '17 at 20:42

2 Answers2

1

Getting the position happens async since the browser needs to get approval from the user. Therefore, you need to call your web service when that happens.

$(document).ready(function(){
  var lon;
  var lat;
  function getLocation(){
    if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition(showPosition);
  }
    else{
      console.log("your device is not suported!");
  }}

  function showPosition(position){
    var pos = position.coords
    lat = pos.latitude;
    lon = pos.longitude;


    console.log(lat); // should not be undefined anymore.
     $.ajax({
       type: 'GET',
       url: 'https://fcc-weather-api.glitch.me/api/current?lat=' + lat + '&lon=' + lon,
       success: function(data){
         $('h1').html( "<strong>" + data.coord.lat + "</strong>" );
         console.log(latitude);
       },
       error: function(error){
         console.log(error);
       }

    });
  }
});
gaheinrichs
  • 565
  • 5
  • 13
0

Well, you just declare showPosition and getLocation . You don't really call them like showPosition() so lat and lon stays undefined