I'm working on a personal project that uses the W3C Geolocation API to retrieve the user's location and then load the weather forecast of that location using Wunderground's API by making an AJAX request. The process is this:
- The user loads the page.
- When the page is loaded, the browser asks to the user to share his location.
- If Geolocation is available, we determine the coordinates and store them in two variables. If not, we jump to the 7th step.
- Those variables (the coordinates) are mixed within another variable (called urlpath) that form a complete URL.
- We make an AJAX request to the JSON API of Wunderground, that request URL contains the variable "urlpath".
- We parse the received JSON and then show the result to the user. Then we are done.
- As geolocation is not available, or is not supported by the browser, we change the value of the "urlpath" variale to the own Wunderground's geolocation and then we make the AJAX request, parse the JSON and show the data to the user.
The problem is that the AJAX request it's done before the "urlpath" variable is configured with the coordinates. It downloads the following file:
http://api.wunderground.com/api/a701d0d2314662c6/undefined.json
Instead of this:
http://api.wunderground.com/api/a701d0d2314662c6/geolookup/q/37.776289,-122.395234.json
Please, can you help me out? I'm kinda newbie to this, but I appreciate your help. Thank you so much.
This is the code:
<!DOCTYPE html>
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0;">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<div class="sliceinfo" id="weather">
<span class="ttitle">The weather</span>
<div id="weathercnt">
<p id="wlocation" class="sliceheadr">Loading location...</p>
<p id="wconsulted">Loading data...</p>
<img id="imgforecast" src="images/loading.gif" class="sliceimg" alt="Some icon">
<div id="detailw">
<p id="tempw"></p>
<p id="windw"></p>
<p id="humidw"></p>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
var KEY = "a701d0d2314662c6";
var urlpath, wlat, wlong;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocation);
}
else {
urlpath = "geolookup/q/autoip.json";
}
function getLocation(position) {
wlat = position.coords.latitude;
wlong = position.coords.longitude;
urlpath = "geolookup/q/" + wlat + "," + wlong ;
}
if (KEY != "a701d0d2314662c6")
{
$.ajax({
url: "http://api.wunderground.com/api/" + KEY + "/" + urlpath + ".json",
async: false,
dataType: "jsonp",
timeout: 4000,
success: function(parsed_json) {
var localw = parsed_json['current_observation']['display_location']['full'].toString();
var temp_c = parsed_json['current_observation']['temp_c'].toString();
var winds = parsed_json['current_observation']['wind_kph'].toString();
var humidw = parsed_json['current_observation']['relative_humidity'].toString();
var iconw = parsed_json['current_observation']['icon'].toString();
var consultw = parsed_json['current_observation']['observation_time'].toString();
$('#wlocation').html(localw);
$('#imgforecast').attr('src', "images/icons/" + iconw + ".png");
$('#tempw').html("<strong>Temperature:</strong> " + temp_c.replace(".",",") + " <sup>ยบ C</sup>");
$('#humidw').html("<strong>Humidity:</strong> " + humidw);
$('#windw').html("<strong>Wind:</strong> " + winds + " Km/h");
$('#wconsulted').html(consultw.replace("Last Updated on","<strong>Updated on: </strong>"));
$('#wlocation').css("font-weight","bold");
},
error: function(request, status, err) {
if (status == "timeout") {
$('#wlocation').html("ERROR");
$('#consultado').html("We were not able to load the information");
$('#imgforecast').attr('src', "http://t3.gstatic.com/images?q=tbn:ANd9GcQzl8g-SPI029d0EUZqW_oFPS8HqQ1yVMTBRZcLzulc51WIEIPn");
} else {
$('#wlocation').html("Error: " + request + status + err);
}
}
});
}
else
alert("Fatal error");
});
</script>
</body>
</html>
The call to
getCurrentPosition
is asynchronous so your Ajax call is made beforeurlpath
is set. The simple fix would be to make the Ajax call from within the callback you supply togetCurrentPosition
: