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

 

 

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!

The Web & Design

Viking Code School Prep Work – Test Yourself

URL – Uniform Resource Locator, the address of a web page
Domain – the website URL
IP Address – Internet Protocol Address, numerical identification label assigned to each device
DNS – Domain Name System, where all domain names are stored
HTTP – HyperText Transfer Protocol
HTTPS – protocol for secure communication
POP & IMAP & SMTP – protocols for mail delivery

  • Post Office Protocol – allows email client to download emails locally from an email server
  • Internet Message Access Protocol – similar to POP3 but also keeps a copy of the email on the server.
  • Simple Mail Transfer Protocol – allows you to send a message to your server and then the server routes to the final destination.

API – Application Program Interface
Web Server – hardware or software that dispenses web pages
Bugs – errors
The Cloud – internet-based computing
Cookies – information that a website puts on your hard disk so that it can remember something about you at a later time
404 Error – server cannot find what was requested
SEO – Search Engine Optimization


Design

WYSIWYG – What you see is what you get
Responsive Design – scale your design for all devices
Grid System – using rows and columns to design your web page
RGB – Red, Green, Blue
Hex – codes colors are labeled with
Above the Fold – the portion of the web page that is visible when the page first loads
GUI – Graphical User Interface
Front End / Back End – front end is what user sees, back end is behind the scenes

How the Web Works

Viking Code School Prep Work Q’s

Web Development Basics

  1. What is the internet?
    The internet is just billions of computers connected through wires run all over the Earth.
  2. How is information broken down and sent?
    Information is sent in packets to an IP address.
  3. What are packets?
    Packets are small bits of information sent over the internet.
  4. What is a “client”?
    You! Your browser or computer. Something that’s able to communicate with a server.
  5. What is a “server”?
    Server is where information is stored.
  6. What is HTTP and how does an HTTP request work?
    Hypertext Transfer Protocol. Protocol browsers and servers use to communicate. Browser will send a GET message across the internet when you enter a web address.
  7. What are DNS servers?
    Domain Name Servers are like a phone book. They hold all the domain names and match them with their IP addresses.
  8. What is HTML and how is it used?
    HTML (Hypertext Markup Language) is used to identify and display content.
  9. What is CSS and how is it used?
    CSS (cascading stylesheets) is used to style content.
  10. What is your browser’s Web Inspector (aka Developer Tools) and how can you use it to poke around in a page’s HTML?
    I use Chrome to see what the content and styling is for each HTML element
  11. What happens behind the scenes after you click “search” on google.com?
    Great explanation here:
    http://www.google.co.in/insidesearch/howsearchworks/thestory/

    Unnamed QQ Screenshot20151209030654

Front-End Interview Questions

I have started applying to junior web developer positions to see if I have the necessary skills to start working. Today I had a call with a recruiter who asked me several questions that I didn’t know the answer to. The position she was trying to place me in was a front-end role so the questions are more geared towards the front-end development of web applications.

The questions:

  1. What are CSS sprites?
    CSS sprites are a way to combine multiple images into one image file to help performance. This way, you only need to load your images with one HTTP request.
    Read more on sprites and how to implement them here.
  2. What is the difference between px and em?
    • px stands for pixels and each pixel represents a dot on your computer screen. Pixels are fixed-size units which means that they are not scale-able to tablets and mobile devices. It’s great to use px for your styling and design, but not for font sizes.
    • em is best to use for scaling font sizes because it adapts to all devices and is very mobile friendly. 1em = default document font size (usually 12pt).

    Kyle Schaeffer explains it best.

     

  3. What is the difference between visibility: hidden and display: none?
    • visibility: hidden hides the element, but the element will still affect the layout and take up the same space.
    • display: none does NOT occupy space on a page. It’s like the element has been removed.

     

  4. What are some JavaScript libraries you’ve used?
    DOM: jQuery, Prototype, MooTools, Dojo
    Web Application Frameworks: Meteor.js, Angular.js, React.js, Ember.js
    GUI: Bootstrap, jQuery UI
    See more here.
  5. What do you do when a browser can’t display HTML5?
    You can make a separate view for browsers that can’t render HTML5. You can also add JavaScript elements to display what you need in case HTML5 isn’t rendered.
    Test if a user’s browser has HTML5 capabilities with Modernizr.js (another JavaScript library!).
    Guide to making Internet Explorer display your HTML5 elements with JavaScript.

 

Want to share your own questions? Leave a comment!

JavaScript String Manipulation Challenge

Going through Udacity‘s free online JavaScript course, I came across this challenge:

Your Challenge

If given a string of a two word name formatted with any mix of capitalization, can you manipulate the string to ensure the first name has a capital first letter and the last name is totally capitalized? Assume there’s a space between the names. For instance, turning a string like "cAmEROn PittMAN" into "Cameron PITTMAN". Your answer should be a single string saved to the variable called finalName.

Take a look at MDN’s documentation on string methods for clues, then try it yourself!

==============================================

My solution:

Unnamed QQ Screenshot20151001081020

The breakdown:

Line 1: var name = "AlbERt EINstEiN";

A variable called name has the value AlbErt EINstEiN. All lines in JS have to end with a semicolon so that the system knows it is the end of a line.

Line 3: function nameChanger(oldName) {

A function called nameChanger will take in an argument called oldName. All functions will start with a curly brace after the function name.

Line 4: var finalName = oldName;

A variable called finalName has the value of oldName.

Line 6:  var nameArray = oldName.split(' ');

The value of oldName is taken and a .split() method is called to make a string array from oldName. The array values are created using a ‘ ‘ (space) as the separator. For example, if
oldName = "AlbERt EINstEiN";
oldName.split(' ');
would equal have the values: [AlbERt', 'EINstEiN']

Then these values would be saved in a new variable called nameArray.

Line 7: var lastName = nameArray[1].toUpperCase();

The second value (since arrays start with 0, nameArray[1] would be the second value) in nameArray is changed to all uppercase letters. This is stored in a new variable called lastName. For example, if
nameArray = ['AlbERt', 'EINstEiN']
nameArray[0] = ['AlbERt']
nameArray[1] = ['EINstEiN']
nameArray[1].toUpperCase();
would be equal to ['EINSTEIN']
var lastName = ['EINSTEIN']

Line 8: var firstName = nameArray[0].toLowerCase().split('');

The first value in nameArray is changed to all lowercase letters. Then the letters will be separated from each other since the .split(”) is an empty string. So if
nameArray[0] = ['AlbERt'],
firstName = ['a', 'l', 'b', 'e', 'r', 't'];

Line 9: var firstLetter = firstName.splice(1).join('');

firstName will start the array from the second value (1) and then the array will be joined together to form one string. For example:
firstName = ['a', 'l', 'b', 'e', 'r', 't'];
firstName.splice(1) = ['l', 'b', 'e', 'r', 't'];
firstLetter = ['l', 'b', 'e', 'r', 't'].join('') = ['lbert'];

.splice() method
.join() method

Line 10: var firstNameJoin = firstName[0].toUpperCase() + firstLetter;

The first value in the array firstName is changed to uppercase, then added to the value of firstLetter.
firstName = ['a', 'l', 'b', 'e', 'r', 't'];
firstName[0] = ['a'];
firstName[0].toUpperCase() = ['A']
firstNameJoin = ['A'] + ['lbert'] = ['Albert'];

Line 12: finalName = firstNameJoin + ' ' + lastName;

finalName = [‘Albert’] + [‘ ‘] + [‘EINSTEIN’] = [‘Albert EINSTEIN’];

Line 14: return finalName;

Saves the value of finalName.

Line 18: console.log(nameChanger(name));

'console.log' will show on the screen whatever is in the parentheses. Inside the parentheses, the function we made, nameChanger, is called with a parameter inserted called ‘name‘. ‘name‘ is the name of the variable that was defined in the beginning on Line 1.

There are many other ways to find a workable solution, so don’t think you HAVE to do it this way.

Ruby | Conditionals and Flow Control

Answering Odin Project questions on Ruby Conditionals and Flow Control:

    • What is a “boolean”?
      A boolean is a binary variable that holds two possible values “true” and “false”
    • What are “truthy” values?
      Objects that are considered true in a boolean are truthy, false are considered falsey. What’s true and false varies across different languages.
    • Are nil, 0, "0", "", 1, [], {} and -1 considered true or false?
      nil -> false, 0->true, “0”->true, “”->true, 1->true, []->true, {}->true, -1->true
    • When do you use elsif?
      When you have more than two parts in an if statement.
    • When do you use unless?
      When you want to test for ‘false’.
    • What does <=> do?
      This ‘spaceship’ operator returns 1, 0, or -1 instead of 1, 0
      For example: a <=> b
      If a < b, return -1.
      If a = b, return 0.
      If a > b, return 1.2 <=> 5, returns -1 because 2 is less than 5.
    • Why might you define your own <=> method?
      When you are sorting an array. You can use it for both integers and strings. Strings are sorted according to the ASCII order and so is case sensitive. Uppercase letters come before lowercase letters.
    • What do || and && and ! do?
      || = logical ‘or’
      Evaluates the first operand. If true, returns true. Otherwise, returns the value of the second operand.

      && = logical ‘and’
      Evaluates the first operand. If false, returns false. Otherwise, returns the value of the second operand

      ! = ‘not’
      If the expression is true, returns false. If the expression is false, returns true.

    • What is returned by puts("woah") || true?
      true
    • What is ||=?
      a ||= b would mean if ‘a’ is false, then set it equal to ‘b’. Otherwise, leave it the same value before running the conditional.
    • What is the ternary operator?
      ? :
      boolean_expression ? true_expression : false_expression
      Returns the true_expression if boolean_expression is true. Otherwise, returns false_expression.
    • When should you use a case statement?
      You should use a case statement when you want to match a value to a manageable number of conditions.

||= explanation: http://ruby.zigzo.com/2013/02/01/wat-double-pipes-equals-in-ruby/
Spaceship Operator: http://www.evc-cit.info/cit020/beginning-programming/chp_07/custom_sort.html
Follow their Web Development course here: http://www.theodinproject.com/ruby-programming/advanced-ruby-building-blocks?ref=lnav

How to create links in Rails

Creating links can be confusing if you are just starting to learn Rails. It is important to understand how your views, controllers, and routes are connected.

If you already have an app you are working on, simply type:

$rake routes

This command will let you see all your routes, how your views connect to your controller, their URLs, and how to link them in your HTML.erb file.

For example, this is mine:
rake routes rails

The ‘Prefix’ column contains the name of the link path that you will use.

The ‘Verb’ column tells you what HTTP actions are connected to each path:

 REST verb GET POST PUT DELETE
Action show create update destroy

The ‘URI Pattern’ column is the URL link

The ‘Controller#Action’ column gives you the name of the controller and the name of the method action connected with the page.

Taking the above information, we can open our ‘views/articles/index.html.erb’ page and start adding links!

Before you start, it is important to understand the difference between <% and <%=. The difference is:

  • <%..%> is for items you DO NOT want to appear in the view (like if statements and iterations).
  • <%=..%> is for items you DO want to appear in the view (like images and links).

To create a link in your html.erb file, you can follow this example:

<%= link_to "Text to show", model_instance %>

It will generate html that looks like this:

<a href="http://www.url.com/model_instance">Text to show</a>

Let’s create our own using the routes listed in our $rake routes using the above example.

<% link_to "New Article", new_article_path %>

The HTML for the link will look like so:

<a href="/articles/new">New Article</a>

To add a class to the link, just include it at the end:

<% link_to "New Article", new_article_path, class: "btn btn-default" %>

To add an image, use the following code recipe:

<%= image_tag('image.jpg') %>

4 Affordable Coding Boot Camps

I am finding it increasingly more challenging trying to improve and learn as a coder. There’s no one to ask questions to or collaborate with, also to help me think in a different way. I’ve reached a point where I realize the limits of self-teaching and how important a collaborative environment is. I’ve been researching affordable boot camps and have found four that seem reasonable.

  1. Recurse Center is a three-month retreat where programmers can go to immerse themselves in a programming environment and work on real-world projects with other attendants. During the three months, you will be studying on your own in a project-based environment, but surrounded by mentors and similar peers. It’s not a boot camp, nor is it for beginners. After the three months, it is possible to get employment from one of the many companies that work with Recurse Center.Recurse Center is located in New York, and with the high cost of living, they offer grants for those who cannot afford to pay housing during the three-month-period. This is definitely something I am able to and want to do.
  2. LAMP Camp is located in Atlanta, Georgia and is similar to Recurse Center in that it let’s you work on real-world projects while you grow as a programmer. Their boot camp program goes for 12-weeks and is sponsored by CRESCA Group, where most of the projects you will be working on come from. What’s great about LAMP Camp is that they teach you how to work on a development team using Agile project management principles. So not just the programming side of things, but also the business side. Instead of focusing on Ruby on Rails, or Javascript, Lamp Camp focuses on PHP and MySQL databases.
  3. Dev Mountain has two locations, one in Provo, Utah, and one in Dallas, Texas. In addition to web development, they offer iOS development and UX Design. Their tuition for the immersive 13-week web development program is pricey, but cheaper than most boot camps at $8,900-9,500. What’s great about their price is it includes a gym membership, HOUSING, and a public transit pass for your time there. With all that included, it’s not bad. Their program focuses on Javascript, with AngularJS, Node.js, React, MongoDB, and more.
  4. App Academy is located in San Francisco and New York City and offers a 12-week immersive full-stack developer boot camp. What’s great about App Academy is you don’t pay any tuition. If you are able to find a job after graduating, they take a one-time placement fee that’s 18% of your salary.  An impressive 98% of their graduates are able to find jobs after graduation. During their program, you will be learning HTML, CSS, Ruby, Rails, jQuery, PostgreSQL, Backbone.js, and Javascript. I’ve applied for their program and let me warn you, it is VERY competitive and also you have to complete a series of programming exercises (20 of them) to even get a phone interview. Not to mention you will also have to do some programming exercises during the in-person interview. They only accept 5% of their applicants and to keep their applicants from dropping out of the free boot camp, they require a deposit of $5,000.