HTML and CSS Reference
In-Depth Information
easier, we'll use the jQuery JavaScript library to help us interface with GeoNames and
update our HTML placeholders ( jQuery offers a set of convenience functions that
greatly simplify both these tasks).
The code for Step 1 should look familiar:
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
get_location();
function get_location() {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(geolocate_story, throw_error);
} else {
alert('Your browser/ereader does not support geolocation. Sorry.');
}
function throw_error(position) {
alert('Unable to geolocate you. Sorry.');
}
}
As we saw in the beginning of the chapter, this code calls the getCurrentPosition()
function to obtain latitude/longitude, with some error handling in place in case the
user's environment doesn't support geolocation, or the geolocation attempt fails. This
time, however, if geolocation succeeds, we'll call the geolocate_story() function to
perform Steps 2 and 3.
In Step 2, we query GeoNames for temperature info:
function geolocate_story(position) {
var geo_lat = position.coords.latitude;
var geo_long = position.coords.longitude;
// Get weather information
$.ajax({
type: 'GET',
url: 'http://ws.geonames.org/findNearByWeatherXML?lat=' + geo_lat + '&lng=' +
geo_long,
dataType: 'xml',
success: function (weather_resp, xmlstatus) {
var temperature_celsius = $(weather_resp).find("temperature").text();
if (temperature_celsius != "") {
// Weather temp data given in Celsius; convert to Fahrenheit, because I'm American
var temperature_fahrenheit = 9/5*temperature_celsius + 32;
$('#weather_temp').text(temperature_fahrenheit);
} else {
$('#weather_temp').text("TEMP NOT FOUND");
}
},
error: function (xhr, status, error) {
alert(error);
$('#weather_temp').text("TEMP NOT FOUND");
}
})
 
Search WWH ::




Custom Search