Local weather app: connecting geolocation with the api

Local weather app: connecting geolocation with the api
0

#1

Hi everyone,

The local weather project is driving me crazy. My javascript code is below, and I am not sure what I am doing wrong. Nothing happens at all when I click my button (#getWeather). But, if I comment out the bottom half of the code, I can get the lat and lon coordinates to appear in my div (#displayBox). Similarly, if I comment out the geolocation part of the code and hard code the coordinates into the openweather api url, then I can get the weather information to display in the div. But when I try to do all of it, something is not working.

I have a feeling it is something trivial I am overlooking, and I can’t figure it out. If anyone has suggestions, I would love to hear them.

Thanks

$(document).ready(function() {
$("#getWeather").on(“click”, function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var x = position.coords.latitude;
var y = position.coords.longitude;
$.getJSON(“http://api.openweathermap.org/data/2.5/weather?lat="+x+"&lon="+y+"&units=imperial&APPID=e9b433f7ed306860db69ea25723a5f48”, function(data) {
var city = data.name;
var temp = Math.round(data.main.temp);
var weather = data.weather[0].description;
var image = “”;
$("#displayBox").html(city+"

"+temp+"

"+weather+" “+image);
});
});
} else {
$(”#displayBox").html(“Unable to access geolocation data.”);
}
});
});


#2

What does the line with the $("#displayBox").html() say exactly? Because it works fine for me without using whatever text you put in between. Also what’s in the image variable?

BTW: Your code will be displayed better, if you select your code and press </> .


#3

Thanks for your reply, and thanks also for the heads up about how to post code. I was wondering how people did that.

On a whim, I decided to switch browsers. Voila! On Firefox my code works perfectly. On Chrome: no so much. I wonder what the problem is?

And here is my code in better form hopefully:

$(document).ready(function() {
  $("#getWeather").on("click", function() {
    if (navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(function(position) {
        var x = position.coords.latitude;
        var y = position.coords.longitude;
        $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+x+"&lon="+y+"&units=imperial&APPID=e9b433f7ed306860db69ea25723a5f48", function(data) {
          var city = data.name;
          var temp = Math.round(data.main.temp);
          var weather = data.weather[0].description;
          var image = "<img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>";
          $("#displayBox").html(city+"<br><br>"+temp+"<br><br>"+weather+" "+image);
        });
      });
    } else {
      $("#displayBox").html("Unable to access geolocation data.");
      }
  });
});

#4

I really wish FCC did a better job explaining this challenge. took me two days to figure out (it was before we had the forums), and I have seen lot of other people here with the same issue.

The problem is, you can’t use navigator.geolocation and the openweather map at the same time. Why? navigator.geolocation requires that the page be loaded in a secure connection (https://). OpenWeatherMap free version does not let you access data if your page is loaded with a secured connection. You will get something like “Mixed content: the page at … requested data from http://… but was loaded over https” something like that in the console. The point is, if you want to use OpenWeatherMap, you cannot use navigator.geolocation. I would recommend using the IP-API - its super simple. Send a request to http://ip-api.com/json like you did with the weather api. You can get everything you need about the user’s position such as lat, lon, etc. from the ip-api object.


#5

Chrome doesn’t support geolocation on insecure sites (http). So you would have to use https, but then your api won’t work, because Chrome will also not let you make http api request on https website. You can work around this by using $.getJSON("https://crossorigin.me/http://api.openweathermap.org/....... and then opening codepen (if you are using that?) with https.


#6

that is an interesting link, just thought I should add, that codepen is not https by default so if someone looks at your portfolio on codepen this will not work.


#7

That’s true. Though most people will only see this after you link to it. But you could add a comment at the top of the HTML/CSS/JS for those people. @BobWinn please note that site (http://crossorigin.me) is quite often down, so the solution of @IsaacAbrahamson might be better


#8

That is great to know. Thanks a lot. I think I will switch over to the ip-api instead.


#9

Two things:

  1. I put code in my codepen where if someone opens it over http, a pop up will appear and tell them to type in https instead.
  2. The downside of using an IP API is that (1) if you’re not on wifi, who knows where it’ll put you–it put my phone ~1500 miles away from where I actually was and (2) even if you’re on wifi, it’ll still sometimes be wrong. What I did instead, because I wanted it to be a functional and practical weather app that I would want to use, is use an API that supports https requests. I used the forecast.io Dark Sky API (they’re the ones that are behind the iPhone weather app), and it came with some cool animated weather icons, too. Just another option if you want it!

#10

Thanks for the reply. Good to know about the downside to the IP API, and I too want this to be a versatile app. I will definitely look into the Dark Sky API.


#11

One thing about the Dark Sky API (everything has a caveat ;))–the location things like the city, state, country, etc. aren’t included in the JSON object, so if you want those, you’ll have to figure out how to get them. I used Google’s geocoding API and input the latitude and longitude to get location info. Just a heads up! :slight_smile: I have seen people who have just printed the latitude and longitude on the weather app instead of city/state/country.


#12

How did you do that? Currently trying to find out how to get that going. Also, did you use Skycons? I am having a difficult time trying to get all this to work correctly. My CodePen is here: https://codepen.io/twhite96/pen/OXEEJG/


#13

Here’s the docs for Google’s Reverse Geocoding API. Try it out for yourself, and feel free to ask any questions once you have.

I did use Skycons. They seem to be showing up fine for me–what’s the issue you’re having with them?


#14

I’ve looked at the API docs but it says I need to display a map? At least that’s what I got out of it.

I am still searching for examples of using the API. Thanks for the tip.


#15

Look at this link: https://developers.google.com/maps/documentation/geocoding/start
Scroll down almost to the bottom, and search ‘Reverse geocoding request and response (address lookup)’.
You’ll find an example there, with longitude and latitude in the URL. (You won’t actually need an API key, it works without it just fine. )
I hope this helps to solve your problem.
Good luck with it!


#16

It looks like you got it to work! Congratulations! I’m working on mine right now…


#17

@gsim2345 Thanks! I looked at the website, and it seems very helpful. Although, how did you input the (https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY)? I just put it in an < a > tag with href, and it won’t work. Any suggestions?