Hi, I’m finding some problems when trying to obtain data from the openweather API, this is the code I’m using:
window.onload = function() {
var APIKey = "1c33ea3828d1c5f7affdb9b68a79840e";
var url = "";
var geoOptions = {
timeout: 10 * 1000
}
navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
function geoSuccess(position) {
var lat = Math.floor(position.coords.latitude * 100) / 100;
var lon = Math.floor(position.coords.longitude * 100) / 100;
url = "api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&APPID="+APIKey;
llamarApi();
};
function geoError(error) {
console.log('Error occurred. Error code: ' + error.code);
};
function llamarApi() {
var req = new XMLHttpRequest();
req.open('GET', url, false);
var target = this;
if (req.status == 200) {
var jsonResponse = JSON.parse(req.responseText);
}
}
};
However, all I get is status = “0” so responseText is always an empty string, any suggestion on how to solve this?
thanks in advance for your help!
LrVch
July 5, 2016, 11:19am
2
Hello, here is an example based on your code
window.onload = function() {
var APIKey = "1c33ea3828d1c5f7affdb9b68a79840e";
var url = "";
var geoOptions = {
timeout: 10 * 1000
}
navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
function geoSuccess(position) {
var lat = Math.floor(position.coords.latitude * 100) / 100;
var lon = Math.floor(position.coords.longitude * 100) / 100;
url = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&APPID="+APIKey;
llamarApi();
};
function geoError(error) {
console.log('Error occurred. Error code: ' + error.code);
};
function llamarApi() {
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.send();
req.onreadystatechange = function() {
console.log(req.status);
if (req.readyState != 4) return;
if (req.status == 200) {
var jsonResponse = JSON.parse(req.responseText);
console.log(jsonResponse);
}
// if (req.status != 200) {
// alert(req.status + ': ' + req.statusText);
// } else {
// alert(req.responseText);
// }
}
}
};
1 Like
Thank you so much for your answer, however I have onather question thanks to your solution.
why does it has to be an asynchronous request? from what I know is better to do async request for performance reasons, but is there any special reason or cases when you should use sync requests?
Oh, also… how can I make this work on Google Chrome? I´m testing it on Safari and works perfectly, but on Chrome it fails on the getCurrentPosition method.