Show the Local Weather – Part 2

Read Part 1 here. Part 1 covers how to get a user’s geolocation to dynamically generate the weather according to the user’s location.

Part 2 is about using the user’s location to get the local weather forecast.

I used OpenWeatherMap‘s API to get the weather information. You’ll need to sign up (it’s free!) and get an API key: http://openweathermap.org/appid

  1. Sign up and get an API key from OpenWeatherMap.
  2. This is an example of the URL (API call) you will use to get weather info:
    http://api.openweathermap.org/data/2.5/weather?lat=33.7708&lon=-84.2931&units=imperial&APPID={APIKEY}

    This is the URL to OpenWeatherMap API:

    http://api.openweathermap.org/data/2.5/weather?

    You can use a city name, city ID, or longitude & latitude coordinates. I decided to use the longitude and latitude for more accurate weather.

    This is where you put the latitude and longitude coordinates.

    lat=11.111&lon=-11.111

    The longitude and latitude coordinates were derived from Part 1:

    {"ip":"8.8.8.8",
    "country_code":"US",
    "country_name":"United States",
    "region_code":"NY",
    "region_name":"New York",
    "city":"New York City",
    "zip_code":"10128",
    "time_zone":"America/New_York",
    "latitude":40.7142700,
    "longitude":-74.0059700,}

    You can also toggle Celsius and Fahrenheit with

    &units=

    Celsius: units=metric
    Fahrenheit: units=imperial

    Read more here.

    In place of {APIKEY} paste your OpenWeatherApp API key. You can find your key when you log into your account and go to the API Keys tab.

  3. Test your API call with Postman by placing the full URL ( http://…APPID=…..) in as a GET request. You should get a response similar to something like this:
    {"coord":{"lon":139,"lat":35},
    "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
    "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
    "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
    "wind":{"speed":7.31,"deg":187.002},
    "rain":{"3h":0},
    "clouds":{"all":92},
    "dt":1369824698,
    "id":1851632,
    "name":"Shuzenji",
    "cod":200}

    Play around with different locations and when it is successful, you can go to the next step!

  4. Start writing your JavaScript function! We need to create an AJAX call to get the data returned from the API and store it in our own variables so we can use the information. I used the jQuery .ajax function.
    function getWeather(url) {
    	$.ajax({
    		url : url,
    		dataType : "json",
    		success : function(data) {		
    			var temp = data['main']['temp'];
    			var image = data['weather'][0]['icon'];
    			var desc = data['weather'][0]['description'];
    			var humidity = data['main']['humidity'];
    			var rain = data['weather'][0]['main'];
                            var sunset = new Date((data['sys']['sunset'])*1000);
                            sunset = sunset.toString().slice(16,21);
                            document.getElementById('image').src="http://openweathermap.org/img/w/" + image + ".png";
    			$('#temp').html(temp);
    			$('#desc').html(desc);
    			$('#wind').html(rain);
                            $('#sunset').html(sunset);
                            $('#humidity').html(humidity + "%");
    		}
    	});
    }

    The sunset variable is storing the sunset UNIX number and converting it to a readable format according to the user’s timezone.

    I am passing in the parameter to getWeather the URL saved as Weather in Part 1. It’s the URL you use to make the weather API call.

To load OpenWeatherMap’s weather icons, use this img source format:

http://openweathermap.org/img/w/" + image + ".png";

Where:

var image = data['weather'][0]['icon'];

Final Product: http://sunsplat.github.io/fcc_weather/index.html

Source for how to get the weather icons here: https://openweathermap.desk.com/customer/portal/questions/13287488-weather-icon-id

Another weather API you can use: forecast.io

Advertisements

Show the Local Weather

This is Part 1 explaning the steps I took to complete the Show the Local Weather challenge from FreeCodeCamp‘s Intermediate Front-End Development Projects section. Part 1 consists of getting a user’s geolocation dynamically. Part 2 Part 2 will be about how to use OpenWeatherMap’s API in your app.

I used Postman to check API connectivity and to get the JSON objects. You can also simply use your browser to do the checks.

  1. First I created the site layout for my weather app using Bootstrap. This way I could play with where I wanted the person’s location to appear and how I wanted to show the weather. I used HTMLshell to quickly paste the usual tags.
  2. I created an empty CSS file and an empty JS file and included the links in my main index.html file.
  3. Then I wanted to add a button that could toggle Celsius and Fahrenheit. I needed to add JavaScript to be able to toggle the action when a user clicks the toggle button.
  4. After getting the button to work, I focused on how to get the user’s location. I used http://freegeoip.net/ to grab a user’s IP address and use that to determine their location. It’s less accurate than Google’s Geolocation, but you can scroll to the bottom to read why that isn’t so simple to implement in Chrome since Spring this year.I knew I was using JSON so I used the url:
    freegeoip.net/json/

    When passing this url, freegeoip will automatically grab the user’s IP and return a JSON object similar to this:

    {"ip":"8.8.8.8",
    "country_code":"US",
    "country_name":"United States",
    "region_code":"NY",
    "region_name":"New York",
    "city":"New York City",
    "zip_code":"10128",
    "time_zone":"America/New_York",
    "latitude":40.7142700,
    "longitude":-74.0059700,}

    If you are using Postman, you can play around with what the response is by sending a GET to:

    //location info for freecodecamp.com
      freegeoip.net/json/freecodecamp.com
    
    //location info for your location
      freegeoip.net/json/
    
    //location info for yahoo.com
      freegeoip.net/json/yahoo.com
  5. Once you are successfully able to get the JSON object info, you can start creating your AJAX call in your JS file. I created a function called getLocation() to contain the information. I used the jQuery function $.ajax to get the data. Can also reference this. Make sure to include the jQuery link in the <head> of your html file or it won’t work!
     https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js

    This is the $.ajax template:

    $.ajax({
      dataType: "json",
      url: url,
      data: data,
      success: success
    });

    This is what my function looks like:

    var locateUser = 'http://freegeoip.net/json/';
    
    function getLocation() {
      $.ajax({
        url : locateUser,
        dataType : "json",
        success : function(data) {
        var country =data['country_code'];
        var region = data['region_code'];
        var city = data['city'];
        var latitude = data['latitude'];
        var longitude = data['longitude'];
        $('#location').html(city + ', ' + region);
        var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=" + OpenWeatherKey;
    getWeather(Weather);
        }
      });
    }

    The ‘#location’ id is tied to the <div> where I want the City, Region to appear on my website.

  6. The next step is to grab the weather for the location data you just stored!

Read Part 2: Getting the Weather Information here.

Final Product: http://sunsplat.github.io/fcc_weather/index.html

Note: When attempting to complete this challenge, do not use Google’s Geolocation as since May 2016, they require do not work over insecure domains (must use HTTPS). Free SSL here.

If you insist on trying to implement Google’s Geolocation, you can sign up for an API key here: https://console.developers.google.com. Then follow Udacity’s really great tutorial on using it: https://www.udacity.com/course/google-maps-apis–ud864.

Keep in mind that Chrome and Safari (webkit browsers) do not allow Geolocation API for files that are local. Geolocation WILL work in Internet Explorer as of this posting.


Another weather API you can use: forecast.io
Another IP geolocation API: http://ipinfo.io/


See https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only for details.

https://www.chromium.org/Home/chromium-security/education/tls#TOC-TLS-Resources-for-Developers-and-Site-Operators

https://mobiforge.com/news-comment/no-https-then-bye-bye-geolocation-in-chrome-50

https://developers.google.com/maps/documentation/geocoding/start?csw=1#reverse

 

 

OpenWeatherMap API in Postman

How to use Postman to test the OpenWeatherMap API:
1. First go to the OpenWeatherMap website, click on ‘Subscribe’ under ‘Current weather data’ and sign up for a free API key:
2. Then when you are logged in, navigate to the API Keys tab:
Unnamed QQ Screenshot20160606225904

3. My key is not showing above, but you would want to copy that key.

4. To learn more on how to use the API key in OpenWeatherApp, you can go here:
http://www.openweathermap.com/appid#use

To make an API call (directions in the URL above), use this example:
http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID={APIKEY}

Where {APIKEY} should be replaced with the key you copied in step 3.

5. Open Postman and past the whole URL into the GET ‘Enter request URL’ field like so:
Unnamed QQ Screenshot20160606230526

You’ll be able to see the object result.

Read more here.

Really helpful intro to API’s.

Random Quote Machine

Today I completed the FreeCodeCamp Zipline: Build a Random Quote Machine!

It took me about two hours, plus an hour of styling to get something that I liked.

This is what the completed machine looks like:

quote

Check it out here.

To approach this Zipline, I broke it down into manageable parts.

  1. I created the HTML file with three main items: my page title, div container where I wanted to put the quotes, and two buttons. I used Bootstrap to get the positioning the way it is.
  2. I then wanted to add text to my currently empty div container so I did a Google search on how to dynamically add text with JavaScript and came across this.
  3. Then I created an array of quotes that could be randomly chosen by their array index number. I pulled a sample of quotes from here.
  4. When a user presses the ‘Another thought’ button, I want a quote from my sample to appear. I did a Google search on how to implement an .onClick event and found this.
  5. To pull randomly, I did a search on how to select random items in an array using jQuery and found this. I created a function to hold the sample array and the random number generator.
  6. To create the Twitter sharing button, I used this to help generate the correct data for my link. If you want to use Twitter’s pre-designed buttons, you can go here to generate code for that.
  7. After I got all that to work, I did the page styling. I used Unsplash for my background image. Go here for a text-shadow lesson.

Whoohoo! Working quote machine!

Bonfire: Falsy Bouncer

Challenge:

Remove all falsy values from an array.

Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.

Use the following:
Array.filter()
Boolean objects


My Solution:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.

  var newArray = [];
  for (var i = 0; i < arr.length; i++) {
    var arrBool = Boolean(arr[i]);
    if (arrBool === true) {
      newArray.push(arr[i]);
      //return newArray;
    }
  }
  return newArray;
}


bouncer([7, "ate", "", false, 9]);

To approach this challenge, I broke it down like this (my thinking process):
1. I need to pass each element of the given array (arr) through a loop to check if each item value is 'false' or 'true'.
2. I can use the Boolean object to check if an item is false or true. I’ll do that within my loop.
3. I don’t know how to use Array.filter(), even after reading the Mozilla page. I’ll ignore that for now.
4. What kind of loop will allow me to iterate through each item in the array? I can use a ‘for loop‘.
5. Do I need to use split()? No, .split() only works for strings.
6. Oh, if you have an array, you can check each individually by using their index number, which starts with 0. So, [0=>7, 1=>”ate”, 2=>””, 3=>false, 4=>9]. Then I’ll start my ‘for loop’ variable ‘i’ at 0 (var i = 0), iterate the length of the array (i< arr.length), and increment by 1 because I want to go through every index in the array (i++).
7. I’ll use an if statement within my loop to check if the values are true or false.
8. After I check if the value is true or false, I want to take all the true values and put them somewhere. Maybe I’ll create a new array called newArray and store all the true values (var newArray = []). I want to be able to return the newArray so I’ll declare this newArray outside of my loop.
8. To add items to an array, you can use .push(), with what you want to push included inside the parentheses.
9. I tried to do newArray = newArray.push(arr[i]); but was getting an error. I removed newArray = and now it works! Will need to look into why that is later.
10. I want to return the new array, so I’ll write return newArray outside of my for loop.
11. I also want to return my newArray in my if statement so that the for loop can access the newArray values.
12. Well, returning the newArray within my if statement causes an error, so I’ll comment that out.
13. Yay! Passed all tests!

FreeCodeCamp in Atlanta

I organized the Atlanta FreeCodeCamp meeting this past Saturday, gathering fellow FreeCodeCampers together to code and pair program. Just saw this post this morning where the Founder of FreeCodeCamp, Quincy Larson, used my picture in his LinkedIn post linking to an answer on Quora. I am ecstatic. I am SO impressed with how involved the founder is with the users of his program. Thanks for promoting the Atlanta group!

Screen Shot 2015-10-20 at 9.17.24 AM

See the Quora post here: “I suck at programming but I love it. What should I do?” Quincy Larson is very active on Quora and I highly recommend signing up and following him.

To attend one of our Atlanta FreeCodeCamp meetups, join the official Facebook Group here: https://www.facebook.com/groups/free.code.camp.atlanta/ We welcome all coders, whether you are going through the online boot camp or not, and are more beginner-focused.

Bonfire: Slasher Flick

Use either .splice() or .slice() to get the answer to this coding challenge from FreeCodeCamp.

The Challenge:

Return the remaining elements of an array after chopping off n elements from the head.

The head meaning the beginning of the array, or the zeroth index


My Solution:

function slasher(arr, howMany) {
  // it doesn't always pay to be first
  arr = arr.slice(howMany, arr.length);
  return arr;
}

slasher([1, 2, 3], 2);

I used the .slice() method and sliced starting at the howMany value, through the length of the array. This challenge took me about ten minutes! Are they getting easier or am I just getting better? I hope it’s the latter!

Bonfire: Factorialize a Number

Factorialize a Number – great JavaScript coding challenge from free online full-stack bootcamp FreeCodeCamp. This was a tough one that required a couple hours to figure out. Taking a break from these challenges really makes them harder when you start back up!

Challenge:

Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120


Solution:

function factorialize(num) {
  var total = 1;
  for (var i = 0; num > i; i++) {
    total = total * (i+1);
  }
  return total;
}

factorialize(5);

Bonfire: Chunky Monkey

The Chunky Monkey Bonfire took me about 40 minutes to solve. It was a real tough one and I had to Google to find some help.  I used the .push() method and the .slice() method. Came across Wulkan’s blog in my search and his solution to the challenge really helped me find mine. Thanks Wulkan!

The Challenge:

Bonfire: Chunky Monkey

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.

For example:
chunk(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]]
chunk([0, 1, 2, 3, 4, 5], 3)
 should return [[0, 1, 2], [3, 4, 5]]


The Solution:

function chunk(arr, size) {

  var newArr = [];
  for (i = 0; i < arr.length;) {
    newArr.push(arr.slice(i, i += size));
  }
  return newArr;
 
}

chunk(["a", "b", "c", "d"], 2, "");

I was having trouble with controlling the incrementation in the ‘for loop’ so I just took out the ‘i++’ and it worked!