0

alert:

Basic javascript question... How can I get the data from the success handling and return a JSON object?

Is there a away that I can place this code:

function Geo() {
    navigator.geolocation.getCurrentPosition(
        function(position) {
            I DONT WANT TO USE position here... 
            I want to place it in a var like so...
            this.data = position; // or something similar?

        },
        function errorCallback(error) {
            //do error handling
        }
    );
}
var geo = new Geo();
geo.????? how can I get that data?

I tried this but it this.data comes back undefined

Inside a function and call that function to get the data? I want to get that data on damand and use that data to populate different fields. I can't always use that data right there and then.

var data = ???
Phil
  • 10,948
  • 17
  • 69
  • 101

1 Answers1

1

I'm assuming that getCurrentPosition() is an AJAX call, so you'll need to define a callback, so your JS execution doesn't just hang while its waiting for it.

function Geo(cb) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
        I DONT WANT TO USE position here... 
        I want to place it in a var like so...
        cb(null, position);
        this.data = position; // or something similar?

    },
    function errorCallback(error) {
        //do error handling
        cb(error);
    }
  );
}



var geo = new Geo(function(err, data){
   //this will be executed once the data is actually ready
   if(err) {
      console.log(err); //handle the error
   } else {
     console.log(data); //handle success
   }
});
Jamis Charles
  • 5,827
  • 8
  • 32
  • 42
  • I am so sad that this is the only solution that javascript provides. Thank you very much. – Phil Dec 26 '13 at 17:43
  • @Phil Sad? What were you hoping for? JS is event based, so this currently is the cleanest way to handle it's event-based nature. This is usually pretty clean. If you are seeing pain from this solution, there may be a better way to solve your problem. – Jamis Charles Dec 26 '13 at 17:47
  • I'm not doing it wrong, I just had a wrong idea of when I wanted the data. This solution, in retrospect, is really nice. – Phil Dec 26 '13 at 19:16