0

I'm using the following code but instead of console.log , I want to use the user_position.lat and user_position.lng in some other section of my code.

         if (navigator.geolocation) {
          var lat_lng = navigator.geolocation.getCurrentPosition(function(position){
           console.log(position);
          var user_position = {};
          user_position.lat = position.coords.latitude; 
          user_position.lng = position.coords.longitude; 
          callback(user_position);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}
getLocation(function(lat_lng){
  //console.log(user_position.lat);
});


I want to use the following outside of a function to get the latitude and longitude 
but always getting an error (user_position.lat not defined)

var lat = user_position.lat
var lng = user_postion.lng

Thank you, Simon

  • Please update with complete code – b.stevens.photo Jul 04 '21 at 00:18
  • I want to use the lat and long in my response API: var responseTwo; responseTwo = getJSON('https://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + long + '&appid=xxxxauthtokenxxxx'); var currentWind = JSON.parse(responseTwo).wind.speed; var currentRain = JSON.parse(responseTwo).rain["1h"]; console.log(JSON.parse(responseTwo)); – Simon Orchanian Jul 04 '21 at 00:26
  • No in your question you have a code sample that is incomplete, also it looks like you're using a callback pattern but dont show it fully implemented, this could be a one line fix. Basically user_position is limited by scope right now and you need to get it to the top scope so that it's usable outside of where it's defined. – b.stevens.photo Jul 04 '21 at 00:33
  • Hmm... I'm not sure since if I just do the console.log in my getLocation function, I see the lat and long shown. I just can't access it out of that scope. Not sure how to get it to the top scope to be usable outside. Thank you. – Simon Orchanian Jul 04 '21 at 00:36
  • Please checkout https://stackoverflow.com/help/minimal-reproducible-example – b.stevens.photo Jul 04 '21 at 01:08
  • @SimonOrchanian "*I want to use the values outside of a function*" - that is impossible. Move the other code that uses them inside the callback, so that it won't get executed before the values are loaded. – Bergi Jul 04 '21 at 01:55

0 Answers0