JavaScript 天气小部件

问题描述

我得到了一个天气小部件应用程序的源代码。它工作了一段时间。我将其配置为使用 API 密钥。所以它第一次尝试就成功了,但是当我将它移到另一个文件夹中以在另一个页面中放置小部件时,它没有用。我检查了控制台,发现 domBody 为空。但我不知道它为什么这么说,因为十分钟前它工作正常。知道如何解决吗? heres the output image

var weather = document.getElementById("weather");
var forcast = document.getElementById("forecast");

function setunits(unit) {
  localStorage.setItem("Units",unit);
}

function getunits() {
  var system = localStorage.getItem("Units");
  if (system != "metric" && system != "imperial") {
    system = window.navigator.language == "en-US" ? "imperial" : "metric";
    setunits(system);
  }
  return localStorage.getItem("Units");
}

function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value) {
    vars[key] = value;
  });
  return vars;
}

function getUrlParam(parameter,defaultvalue){
  var urlparameter = defaultvalue;
  if(window.location.href.indexOf(parameter) > -1){
    urlparameter = getUrlVars()[parameter];
  }
  return urlparameter;
}

var keyid = getUrlParam('key','empty');

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(getcoordinates,showError); }
  else {
    x.innerHTML = "Geolocation is not supported by this browser."; }
}

      function getcoordinates(position) {
        getweather(position.coords.latitude,position.coords.longitude)
      }

function showError(error) {
  var errorMessages = {
    PERMISSION_DENIED    : "User denied the request for geolocation.",POSITION_UNAVAILABLE : "Location information is unavailable.",TIMEOUT              : "The request to get user location timed out.",UNKNowN_ERROR        : "An unkNown error occurred."
  };
  weather.innerHTML = errorMessages.UNKNowN_ERROR
  for (var msg in errorMessages)
    if (error[msg] === error.code)
      weather.innerHTML = errorMessages[msg]
}

      var getJSON = function(url,callback) {
        var request = new XMLHttpRequest();
        request.open('GET',url,true);
        request.responseType = 'json';
        request.onload = function() {
          var code = request.status
          if (code >= 200 && code < 400) {
            callback(request.response);
          }
          else {
            callback(null);
            console.log(code)
          }
        };
        request.send();
      };

function localize (units) {
  if (units == "imperial") {
    displayweather(units,"F","mph")
  }
  else {
    displayweather(units,"C","km\/h")
  }
}

function handleCache() {
  var data_timestamp=Math.round(Date.Now() / 1000);
  var unitsystem = getunits();
  if (localStorage.getItem("timestamp") && localStorage.getItem("timestamp") <= data_timestamp - 1800) {
    localize(unitsystem);
  }
  else {
    localStorage.timestamp = data_timestamp;
    getLocation();
  }
}

function displayweather(unitsystem,temp_unit,wind_unit) {
  var data;
  try {
    data = JSON.parse(localStorage.getItem("weather-" + unitsystem));
  }
  catch (exception) {
    if (window.console) {
      console.error(exception);
    }
    return;
  }
  let DomBody = document.querySelector('#bodycontent');
  DomBody.style.background = "url('/images/weather/" + data.current.weather[0].icon + ".jpg') no-repeat fixed 50% 50%";
  DomBody.style.backgroundSize = "cover";
  weather.innerHTML = '<h2>Current Weather</h2><img class="icon" src="/images/weather/' + data.current.weather[0].icon + '.png"><span id="temp">' + Math.round(data.current.temp) + '&deg;' + temp_unit + '</span><p id="description"></p><p>max: ' + Math.round(data.daily[0].temp.max)  + '&deg;' + temp_unit + ' &nbsp;&nbsp;&nbsp;&nbsp;min: ' + Math.round(data.daily[0].temp.min) + '&deg;' + temp_unit + '</p>'
}

function getweather(LAT,LON) {
  var unitsystem = getunits();
  var APIurl = 'https://api.openweathermap.org/data/2.5/onecall?lat=' + LAT + '&lon=' + LON + '&exclude=minutely,hourly&units=' + unitsystem + '&APPID=' + keyid
  console.log(APIurl)
  getJSON(APIurl,function(data) {
    if (data == null) {
      if (keyid == "empty"){
        forcast.innerHTML = 'You need to add an API key to the url. `example.com?key=&lt;api&gt;`' }
      else {
        forcast.innerHTML = 'There was a problem with the request' }
    }
    else {
      localStorage.setItem("weather-" + unitsystem,JSON.stringify(data));
      localize(unitsystem);
    }
  });
}

window.onload=handleCache();
/* Global Settings */

article {
    text-align: center;
    background: rgba(255,255,.4);
    width: 250px;
    margin: 2em auto;
    
    border: 1px solid #aaa;
    border-radius: 15px;
    font-weight: 100 !important;
}
h2 {margin-bottom: 1.5em;}
p,h2 {font-size: 18px; font-weight: 100;}
/* Units Toggle */
#toggle {padding: 0em 2em;float: right;}
#metric {border-top-left-radius: .3em;border-bottom-left-radius: .3em;}
#imperial {margin-left: -.26em;border-top-right-radius: .3em;border-bottom-right-radius: .3em;}
/* Weather Data Styles */
.icon {
    display:inline;
    vertical-align:middle;
    margin-top: -1.5em;
    width: 48px;
}
#temp {font-size: 28px;}
#units {font-size: 2em;vertical-align: super;}
#description,#daily {font-weight: bold;}
<!DOCTYPE html>
<html>
  <head>
    <Meta charset="utf-8">
    <title>Local Weather</title>
    <Meta description content="Get your local weather using geolocation">
    <Meta name=viewport content="width=device-width,initial-scale=1">
    <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.min.css">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Arimo:400,700">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body id="content">
    <article>
      <section id="weather">
        <img alt="loading" id="spinner" src="assets/spinner.gif">
      </section>
      <section id="forecast">
        <noscript>This application requires JavaScript to function. Please enable scripts in your browser.</noscript>
      </section>
    </article>
    <script src="weather.js"></script>
  </body>
</html>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)