0

I am trying to run a JavaScript/JQuery function that pulls the timezone field from a JSON request from the DarkSky API. Currently, my code works by getting the lat and long and passing them into the URL so that the JSON can be received from the DarkSky API.

Currently, I have verified that I am getting lat and long variables and also that the URL is correct and received JSON. However, I am unable to place the timezone field into the tag within my webpage.

Below is my source code:

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>

EDIT:

Below is a snippet of the JSON I have pulled:

{ "latitude": 39.9145429, "longitude": -86.02194999999999, "timezone": "America/Indiana/Indianapolis", "currently": { "time": 1534743029, "summary": "Clear", "icon": "clear-night", "nearestStormDistance": 8, "nearestStormBearing": 219, "precipIntensity": 0, "precipProbability": 0, "temperature": 70.61, "apparentTemperature": 71.17, "dewPoint": 64.44, "humidity": 0.81, "pressure": 1014.05, "windSpeed": 5.1, "windGust": 9.07, "windBearing": 100, "cloudCover": 0.12, "uvIndex": 0, "visibility": 10, "ozone": 295.59 }, "minutely": { "summary": "Clear for the hour.", "icon": "clear-night", "data": [ { "time": 1534743000, "precipIntensity": 0, "precipProbability": 0 },

...............

Dr_Berry721
  • 69
  • 2
  • 11

2 Answers2

0

here's a working code snippet ...

/* 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>
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
  • Thanks for the keyword issue/clarification. – Dr_Berry721 Aug 20 '18 at 05:29
  • However, the solution you provided is not working. I do have a question however, since the timezone field is within the JSON, would I not be able to access it in the way I am attampting? My knowledge was that with the getJSON method you could pull anything from a JSON file. – Dr_Berry721 Aug 20 '18 at 05:32
  • according to the documentation, it works exactly alike this ... failure to apply does not imply that it would be "not working" (this is no accurate error description, at all). what does `console.dir(response)` say ?? besides it is pointless trying to get the timezone from the response, because it should be known at request time, already. – Martin Zeitler Aug 20 '18 at 05:58
  • Nothing appears in the console using console.dir(response), I have also tried .log function and still nothing .... also, I am using time zone just to ensure I am able to pull from the Json before pulling the actual weather info I need. (Yes, I have tried to pull other fields such as response.currently.summary) – Dr_Berry721 Aug 20 '18 at 06:07
  • @Dr_Berry721 see the updated answer & please accept it. – Martin Zeitler Aug 20 '18 at 08:50
  • @Dr_Berry721 `dataType: 'jsonp'` was required, because the server does not send the proper headers with the response. – Martin Zeitler Aug 20 '18 at 15:41
  • I see, quick minor question, It seems to be getting the incorrect lat and lng for my position, any suggestions on how to fix this? – Dr_Berry721 Aug 20 '18 at 15:43
  • Actually never mind, the 2nd loc.coords is incorrect, should be loc.coords.longitute – Dr_Berry721 Aug 20 '18 at 15:44
0

Maybe you should try the link? I think the API should include the forecast as I try from the document example from darksky.

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

I also found error "No 'Access-Control-Allow-Origin' header is present on the requested resource." when trying your example code. Maybe you should also check if you got this error too. And I found some (maybe) source that may solve this problem.

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

I finally come up with a solution using AJAX, hope it helps.

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();
  • Where can I see if I am getting the "No Access-Control-Allow-Origin Error"? Also, I have tried you AJAX solution and seem to still not be getting any results. – Dr_Berry721 Aug 20 '18 at 05:29
  • Sidenote, I am using Visual Studio 2017 – Dr_Berry721 Aug 20 '18 at 05:29
  • I just tested it on the codepen :P [codepen](https://codepen.io/chanandrew96/pen/YOKOmM) I found the error when I debug it using the console in the browser – Andrew Chan Aug 20 '18 at 06:40
  • I guess you can't get the result caused by the "No Access-Control-Allow-Origin Error" issue since the domain is different and the response could be blocked. – Andrew Chan Aug 20 '18 at 06:43
  • Still being new here :P Don't know how to add a snippet – Andrew Chan Aug 20 '18 at 09:06