Retrieving Weather Data
Duration: 25 to 35 minutes.
In this exercise, you will allow visitors to the Nan & Bob's site to find weather conditions for their current location. The result will look something like this:
- Open IntegrationPhone/Exercises/index.html in a file editor.
- Add a button to the home page with id findweather and label "Local Weather".
- Note that a new page (#weather) has been added for you; it contains a listview with id weatherconditions.
- Using the demo above as an example, write code to call the Geolocation API getCurrentPosition function when the user clicks the button.
- On successful retrieval of the user's location, use the $.getJSON function to retrieve weather data; the URL supplied should be of the format ws.geonames.org/findNearByWeatherJSON?lat=43.048122&lng=-76.147424 but, of course, with the user's latitude and longitude.)
- GeoNames will return an object with the weather data - use $.each to iterate over the fields and add each name/value pair to the weatherconditions listview.
- Change the page to #weather and refresh the #weatherconditions listview.
- Be sure to test your code in a mobile browser.
We add a handler to listen for clicks on the
#findweather button, calling
navigator.geolocation.getCurrentPosition. A successful geolocation calls
search function requests JSON data from GeoNames, sending the user's latitude and longitude as part of the request URL. We iterate over the object returned to populate the
#weatherconditionslistview with the results.