I am very new to programming Pebble watches. I have been doing it for 3 hours now. I am stuck trying to assign the latitude and longitude to variables. Hopefully this is just a simple Javascript issue and not a Pebble SDK related issue.
Here is my code:
var lat;
var lon;
var myAPIKey = REDACTED;
var city = 'Boston';
function success(pos) {
console.log('lat= ' + pos.coords.latitude + ' lon= ' + pos.coords.longitude);
lat = pos.coords.latitude;
lon = pos.coords.longitude;
}
function error(err) {
console.log('location error (' + err.code + '): ' + err.message);
}
// Choose options about the data returned
var options = {
enableHighAccuracy: true,
maximumAge: 10000,
timeout: 10000
};
// Request current position
navigator.geolocation.getCurrentPosition(success, error, options);
console.log(lat+'||||'+lon);
When I run the code on the CloudPebble Emulator this the log info:
[PHONE] pebble-app.js:?: undefined||||undefined
[PHONE] pebble-app.js:?: lat= 39.0437 lon= -77.4875
Am I not storing the latitude and longitude correctly. I want to use the data for global use. You can see that it doesnt store the lat
and lon
values, but it does actually run from the consol.log
function.
Since determining the position can take a while, getCurrentPosition()
doesn't run synchronously. Instead it takes one function (the success
parameter) to call when it (eventually) managed to acquire the location, and one function (the error
parameter) when it failed to do so (GPS or Wifi can't be reached or is turned off, etc).
Your code does store the values into your lat
and lon
variables properly, but this only happens at a later point. Or in other words: Your
console.log(lat+'||||'+lon);
is called before the success
function runs. At that time the values are not yet filled.
This is a common JavaScript approach to deal with long running operations. Other objects like XMLHTTPRequest
work exactly the same way.