Tutorials from Pebble developer website
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.0 KiB

  1. var xhrRequest = function (url, type, callback) {
  2. var xhr = new XMLHttpRequest();
  3. xhr.onload = function () {
  4. callback(this.responseText);
  5. };
  6. xhr.open(type, url);
  7. xhr.send();
  8. };
  9. function locationSuccess(pos) {
  10. // generic API key, has to be replaced by developers one
  11. var api_key = 'bd82977b86bf27fb59a04b61b657fb6f';
  12. // Construct URL
  13. var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
  14. pos.coords.latitude + '&lon=' + pos.coords.longitude +
  15. '&APPID=' + api_key;
  16. // Send request to OpenWeatherMap
  17. xhrRequest(url, 'GET',
  18. function(responseText) {
  19. // responseText contains a JSON object with weather info
  20. var json = JSON.parse(responseText);
  21. // Temperature in Kelvin requires adjustment
  22. var temperature = Math.round(json.main.temp - 273.15);
  23. console.log('Temperature is ' + temperature);
  24. // Conditions
  25. var conditions = json.weather[0].main;
  26. console.log('Conditions are ' + conditions);
  27. // Assemble dictionary using our keys
  28. var dictionary = {
  29. 'KEY_TEMPERATURE': temperature,
  30. 'KEY_CONDITIONS': conditions
  31. };
  32. // Send to Pebble
  33. Pebble.sendAppMessage(dictionary,
  34. function(e) {
  35. console.log('Weather info sent to Pebble successfully!');
  36. },
  37. function(e) {
  38. console.log('Error sending weather info to Pebble!');
  39. }
  40. );
  41. }
  42. );
  43. }
  44. function locationError(err) {
  45. console.log('Error requesting location!');
  46. }
  47. function getWeather() {
  48. navigator.geolocation.getCurrentPosition(
  49. locationSuccess,
  50. locationError,
  51. {timeout: 15000, maximumAge: 60000}
  52. );
  53. }
  54. // Listen for when the watchface is opened
  55. Pebble.addEventListener('ready',
  56. function(e) {
  57. console.log('PebbleKit JS ready!');
  58. // Get the initial weather
  59. getWeather();
  60. }
  61. );
  62. // Listen for when an AppMessage is received
  63. Pebble.addEventListener('appmessage',
  64. function(e) {
  65. console.log('AppMessage received!');
  66. getWeather();
  67. }
  68. );