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

I played with the {X} api and I'm trying to get some location data, but as far as I try, I can’t figure out how to get / 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 changing location. How to get current location data (I'm sure there should be a way).

My current code is:

 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 are both "undefined" when I check their contents. (because the device is not moved.)

+4
source share
1 answer

So, after playing with api for a while I realized where I was wrong.

I needed to add my definition of any data I want to get from location data AFTER locListener.stop(); , although I don’t quite understand why and how it works, this is a fix, and the following code works for me. (I also added some card 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(); 
+4
source

All Articles