Getting the current location of a device using the on{X} api

769 views Asked by At

I've been playing with the on{X} api and i'm trying to get some location data however as much as I try I cannot figure out how to get the /current/ location.


Documentation:

This is their example:

    // create GPS listener with update interval of 5 sec  
    // you also use CELL or PASSIVE providers here  

    var listener = device.location.createListener('GPS', 5000); 

    // register on location changed  

    listener.on('changed', function(signal) {  

    // on receiving location print it and stop the provider 

       console.info('Lat: ' + signal.location.latitude);  
       console.info('Lon:' + signal.location.longitude);  
       listener.stop();  
    });

    // start the GPS listener 

    listener.start();

However it seems that this only works when the location is changed. How would I get the current location data (I'm sure there must be a way).

My current code:

var lat;
var lon;
listener.on('changed', function (signal) {
var lat = signal.location.latitude;
var lon = signal.location.longtitude;
listener.stop();
});
listener.start();
//the rest of my code which just sends the data back to a webserver (this bit works)

however both lat and lon register as 'undefined' when i check their contents. (because the device hasn't moved.)

1

There are 1 answers

0
Michael Zaporozhets On BEST ANSWER

So after playing around with the api for a while i figured out where I went wrong.

I needed to add my definition of whatever data i want to access from the location data AFTER locListener.stop();, although I don't entirely understand why or how this works it is a fix and the following code works for me. (I've also added some map stuff ;) )

var loc;
var locListener = device.location.createListener('CELL', 100);

locListener.on('changed', function (signal) {
    // stop listening to location changed events after getting the current location
    locListener.stop();

    var mapUrlPattern = 'https://feeds.onx.ms/maps?wp=lat,lon';
    var mapUrl =  mapUrlPattern.replace(/lat/g, signal.location.latitude).replace(/lon/g, signal.location.longitude);

    loc = mapUrl;
});

locListener.start();