将JQuery与DarkSky API结合使用-不提取数据

时间:2018-08-20 00:48:32

标签: javascript jquery json api

我正在尝试运行一个JavaScript / JQuery函数,该函数从DarkSky API的JSON请求中提取时区字段。目前,我的代码通过获取经度和纬度并将其传递到URL中来工作,以便可以从DarkSky API接收JSON。

当前,我已经验证我得到了lat和long变量,并且该URL正确并且接收了JSON。但是,我无法将时区字段放入网页内的标签中。

下面是我的源代码:

HTML:

<p id="timezone">Summary</p>
<span class="weather-location" id="currentLocation">Current Location</span>

Javascript / JQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    var currentLoc = document.getElementById("currentLocation");
    var tz = document.getElementById("timezone");
    var url = "";

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            currentLoc.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        var lat = position.coords.latitude;
        var long = position.coords.longitude;

        currentLoc.innerHTML = "Latitude: " + lat +
            "<br>Longitude: " + long;

        url = "https://api.darksky.net/[API_KEY]/" + lat + "," + long;

        getTodaysWeather(url);
    }

    function getTodaysWeather(url) {
        $(document).ready(function () {
            $.getJSON(url, function (results) {
                tz.innerHTML = results.timezone;
            });
        });
    }


</script>

编辑:

以下是我提取的JSON的代码段:

{   “纬度”:39.9145429,   “经度”:-86.02194999999999,   “时区”:“美国/印第安纳州/印第安纳波利斯”,   “目前”: {     “时间”:1534743029,     “ summary”:“清除”,     “ icon”:“晴朗的夜晚”,     “最近的暴风雨距离”:8     “最近的暴风雨轴承”:219,     “ precipIntensity”:0,     “ precipProbability”:0,     “温度”:70.61,     “ apparentTemperature”:71.17,     “露点”:64.44,     “湿度”:0.81,     “压力”:1014.05,     “ windSpeed”:5.1,     “ windGust”:9.07,     “ windBinging”:100,     “ cloudCover”:0.12,     “ uvIndex”:0,     “可见度”:10,     “臭氧”:295.59   },   “分钟”:{     “ summary”:“清除时间。”,     “ icon”:“晴朗的夜晚”,     “数据”:[       {         “时间”:1534743000,         “ precipIntensity”:0,         “ precipProbability”:0       }

......

2 个答案:

答案 0 :(得分:0)

这是一个工作代码段...

/* insert your secret here */
var secret = "";

var baseUrl = "https://api.darksky.net/forecast/" + secret + "/";
var defLat = 37.8267; var defLng = -122.4233;

$(function() {

  if (navigator.geolocation) {
    console.log('browser geolocation would be theoretically supported by the browser.');
    navigator.geolocation.getCurrentPosition((loc) => {
      fetchData(baseUrl + loc.coords.latitude + ',' + loc.coords.latitude);
    },
    function (error) { 
      if (error.code == error.PERMISSION_DENIED) {
        console.log("geolocation request had been denied; check your browser\'s settings (this does not work in such a code snippet).");
        console.log("looking up the default location instead, which is " + defLat + ', ' + defLng + ".");
        $("#currentLocation").html("Latitude: " + defLat + ', Longitude: ' + defLng);
        fetchData(baseUrl + defLat + ',' + defLng);
      }
    });
  } else {
      $("#currentLocation").html("Geolocation is not supported by this browser.");
      console.log("geolocation not supported");
  }
});

function fetchData(url) {
  $.ajax({
    url: url,
    dataType: 'jsonp',
    crossDomain: true,
    success: function(data, status) {
      if(status === 'success') {
        $("#currentLocation").html("Latitude: " + data.latitude + ', Longitude: ' + data.longitude + ', Timezone: ' + data.timezone);
        console.log(data);
      }
    }
  });
}
html, body {
  height: 100%;
  width: 100%;
}

div#currentLocation {
  background-color: #CCCCCC;
  vertical-align: center;
  width: 100%;
  padding: 8px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="currentLocation"></div>

答案 1 :(得分:0)

也许您应该尝试链接? 我认为,如我从darksky的文档示例中尝试的那样,API应该包含预测。

  

https://api.darksky.net/forecast/[API_Key]/lon,lat

我还发现错误“请求的资源上没有'Access-Control-Allow-Origin'标头。”在尝试示例代码时。也许您还应该检查是否也收到此错误。 而且我发现了一些(也许)可以解决此问题的资源。

  

Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?

我终于想出了一个使用AJAX的解决方案,希望对您有所帮助。

var currentLoc = $("#currentLocation");
var tz = $("#timezone");
var url = "";

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    currentLoc.html("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  var lat = position.coords.latitude;
  var long = position.coords.longitude;

  currentLoc.html("Latitude: " + lat + "<br>Longitude: " + long);

  url = "https://api.darksky.net/forecast/[API_Key]/" + lat + "," + long;
  getTodaysWeather(url);
}

function getTodaysWeather(url) {
  $.ajax({
     url:url,
     dataType: 'jsonp',
     jsonp: 'callback',
     success:function(json){
       tz.html(json.timezone);
     },
     error:function(){
         //ErrorHandling
     },
});
}

getLocation();