Openweather API returns status = 0

Openweather API returns status = 0
0.0 0

#1

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!


#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);
      // }
    }
  }
};

#3

Thank you so much for your answer, however I have onather question thanks to your solution.

  1. 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?

  2. 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.


#4

1 - http://stackoverflow.com/questions/5528852/ajax-sync-and-async-difference
2- https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only