This is the second part in a series on developing a simple Fitbit Smartwatch App. Now that we have the current location of our user, we can query the weather API. If you missed Part 1, please check it out first! Each part builds on the last part in the series.
- Create a new file named remoteAccess.js in the companion folder.
- Define the API service you want to query, I will use the National Weather Service but you can feel free to use any service you prefer.
const API_URL = "https://api.weather.gov"
- Create the getForecast() function.
async function getForecast(currentLocation) {
const forecasturl = API_URL + "/points/" + currentLocation
console.log(forecasturl)
var response = await fetch(forecasturl)
var forecast = (await response.json()).properties.forecast // Parse the returned object
console.log("Current location forecast: " + forecast)
}
The asynchronous function takes the current location and makes a call to the national weather service with the Fetch API. It returns a URI of the nearest gridpoints, complete with a 14 day forecast.
- Export the getForecast() function for use in the companion index.js file.
export { getForecast }
- Now import the function in the index.js module.
- Call the getForecast() function with the current GPS location.
import { getForecast } from "/project/companion/remoteAccess.js"
function locationSuccess(position) {
current_location = position.coords.latitude + "," + position.coords.longitude
console.log("Current location: " + current_location);
getForecast(current_location);
}
- Try moving your location around in the Fitbit OS Simulator and see the results in the console!
- Add the following lines to the getForecast() function to query the forecast.
response = await fetch(forecast)
forecast = (await response.json()).properties.periods // Parse the returned object
console.log("14 Days: " + JSON.stringify(forecast))
Finally, return the JSON object.
return forecast
In Part 3, we will send the forecast to the watch for display. As always, the project source code is listed on GitHub.
Leave a comment