Skip to content
  • Works
  • Services
  • About
  • Blog
  • Contact

Start free trial

We bring together everything that’s required to build websites. Reach more customers, save time and money, and boost sales.

Edit Content

    • Facebook
    • Instagram
    • Twitter
    Purchase Theme
    AngularJS, blog, Web development

    AngularJS weather forecast Widget [Part 1]

    March 30, 2014 M. Mahbubur Rahman No comments yet

    Ok, we’re going to create this today.

     

    AngularJS weather Widget

    Demo View It Online
    Download Source Files

     

    And we’re going to achieve this using

    1. AngularJS
    2. Twitter Bootstrap 3
    3. Open Weather Map API
    4. CSS3

    Of course we can make similar things using only jQuery but let’s make something cool and learn some stuff on the way.

     

    So, a weather widget, huh. Luckily there are APIs where we can get our weather based on location for free. In today’s example we’re going to use http://www.openweathermap.org/API to get the weather data. But there’s a tiny problem (for the basic version of course) to get your location. The API requires you to supply the location of your city, country. We all want our own weather, right ? These are the options we have.

     

    1. Manually supply the location in a text box
    2. Use HTML5 Geo Location API (but it won’t give you city, just lon/lat and then you feed into Google map for GeoCoding)
    3. Use a third party API to get the location.

    For our case today, the last option is easier. There are couple of web services where you just send a json call and they give you your location. Like

     

    1. http://ip.pycox.com/json
    2. http://freegeoip.net/

     

    I’m going to use a different one – Muslim Prayer times (which i have used in another angularJS post). So it’s http://muslimsalat.com/daily.json

     

    So the app flow will be

     

    Request Geo Location Service => Request weather Service from resolved Geolocation => Print Results . Simple

     

    Now, let’s get into coding business. As a Disclaimer, i want to mention that this part of the project didn’t use all the standards – which we’ll do in another post using Grunt and all that.

     

    So we have this one file which has controller, services and router.

    [cc lang=”javascript” height=350]
    var App = angular.module(“weatherApp”, [‘ngRoute’, ‘ngAnimate’, ‘weatherControllers’, ‘weatherServices’]);

    App.config([‘$routeProvider’, ‘$locationProvider’,
    function($routeProvider, $locationProvider) {
    $routeProvider.when(‘/’, {
    templateUrl: ‘js/views/weather.html’,
    controller: ‘GetWeatherCtrl’
    });
    }
    ])

    var weatherControllers = angular.module(“weatherControllers”, []);
    weatherControllers.controller(“AppController”, [‘$route’, ‘$routeParams’, ‘$location’,
    function($route, $routeParams, $location) {

    }
    ]);

    weatherControllers.controller(“GetWeatherCtrl”, [‘$scope’, ‘weatherApi’,
    function($scope, weatherApi) {
    $scope.currentTime = moment().format(‘h:mm a’);
    weatherApi.getLocation().then(function(res) {
    weatherApi.getWeeklyWeather(res.data.city+”,”+res.data.country_code).then(function(response) {
    $scope.data = response.data;
    if ($scope.data.list.length) {
    $scope.data.list.forEach(function(i, v) {
    var date = moment(i.dt * 1000);
    i.dt = {
    day: date.format(“ddd”)
    };
    if (moment().format(“d”) == date.format(“d”)) {
    i.dt.today = true;
    }
    });
    }
    });
    });
    }
    ]);

    var weatherServices = angular.module(‘weatherServices’, []);

    weatherServices.factory(‘weatherApi’, [‘myHttp’,
    function(myHttp) {
    return {
    getLocation: function() {
    return myHttp.jsonp(“http://muslimsalat.com/daily.json?callback=JSON_CALLBACK”);
    },
    getWeeklyWeather: function(city) {
    return myHttp.get(‘http://api.openweathermap.org/data/2.5/forecast/daily?q=’+city+’&mode=json&units=metric’);
    }
    }
    }
    ]);

    weatherServices.factory(‘myHttp’, [‘$http’, ‘myCache’,
    function($http, myCache) {

    var headers = {
    ‘cache’: myCache,
    ‘dataType’: ‘json’
    };
    var APPID = “bc1e24c531732375aece237bb2a5d49a”;
    return {
    config: headers,
    get: function(url, success, fail) {
    return $http.get(url + “&APPID=” + APPID, this.config);
    },
    getLocal: function(url, success, fail) {
    return $http.get(url);
    },
    jsonp: function(url, success, fail) {
    return $http.jsonp(url, this.config);
    }
    };
    }
    ]);

    weatherServices.factory(‘myCache’, function($cacheFactory) {
    return $cacheFactory(‘myCache’, {
    capacity: 100
    });
    });

    function JSON_CALLBACK(){
    // Nothing
    }
    [/cc]

    So we have one controller named GetWeatherCtrl, One Service weatherServices for API calls and a custom http wrapper so that we can change from http to resource or some other method if we want. As you can see in the top part the App is configured with dependencies and a single route, since we don’t have any other pages.

     

    And there we have a service called weatherApi where we call the API to return the json and it will return the promise by the custom http wrapper we’re using. It’s in the very basic now. For authenticated API services, it becomes handy when you have to send some credentials with all requests.

     

    In the controller if you notice, we have put the weather call after the geo location resolution. So the weather API will wait for being called for the geolocation to be resolved. The muslimsalat.com’s API availability is quite high and without limits. So it gives accurate result most of the times.

     

    In the view, we have use a bootstrap structure. weather.html partial has all the necessary codes where we have separated today and rest of the days. So there are two columns grid

    [container] 
    [ 2 column ] Today [/2 column ]
        [ 10 column ]
            [12 column divided into 6 columns ]
        [ /10 column ]
    [/container]

     

    Btw, we used the awesome library for date calculation/formatting moment.js – for easy time/date formating. Who cares 5.5kb these days anyway ?

     

    That’s pretty much it. Next we’ll do some more awesome things with this widget

     

    1. Add Google map to choose any location for weather
    2. Add multi series D3 charts for weekly weather presentation
    3. Add tooltips for more information on days
    4. Add icons based on weather conditions

     

    So keep checking us

     

    • angularjs
    • api
    • javscript
    • weather
    M. Mahbubur Rahman

    Post navigation

    Previous
    Next

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Search

    Categories

    • Agency (1)
    • AngularJS (5)
    • blog (7)
    • Branding (2)
    • Competitive Marketing Analysis (1)
    • Design (4)
    • Development (10)
    • JS (3)
    • Keywords Analysis (1)
    • Keywords Research (1)
    • Latest News (3)
    • Life at iViveLabs (2)
    • Lifestyle (1)
    • Marketing (6)
    • Onpage Optimization (1)
    • Photography (3)
    • SEO (6)
    • Travel (3)
    • Web development (2)

    Tags

    angularjs api Apple Mac Pro Desktop badmintion beautyful flowers of darjeeling beauty of darjeeling competitive audit report competitive marketing analysis filters flowers of darjeeling get more conversion get more traffic impression from pinterest internet marketing analysis report ivivelabs javascript javscript journey keywords research and analysis link assistant maowa Mawa more conversion more traffic natural beauty darjeeling New Pinterest Web Analytics organic keywords organig keywords research pagination Pagination In AngularJS panam nagar Pin My Post pinterest impression SEO seo audit report Show More Pagination In angularJS sonargaon stories The Future Of The Pro Desktop Track Pinning Activity travel typekit weather wordpress wp-cli

    Related posts

    AngularJS, JS

    Pagination in AngularJS for Typekit API – Show More Pagination in AngularJS

    March 4, 2013 M. Mahbubur Rahman No comments yet

    Pagination in web applications is a very common phenomenon and frequently used to split large result set into pages. The evolution of pagination with creativity has brought us from [1,2,3] to automatic pagination (like you see on google images). Naturally the number based pagination is becoming less and less common these days. We are seeing […]

    AngularJS, JS

    How to make a custom filter in AngularJS ?

    February 26, 2013 M. Mahbubur Rahman No comments yet

    AngularJS is a great open-source JavaScript Framework maintained by Google. This framework has got some compelling features. Filters is one of them for formatting the data in users locale. So we’ve decided to write a simple custom angular filter to sort clients table filtered by company. Demo View It Online Download Source Files At first, […]

    AngularJS, JS

    Making a Quick RSS Feed Reader using AngularJS

    February 20, 2013 M. Mahbubur Rahman No comments yet

    Since AngularJS is the default JavaScript Framework for Front End Application at iVive, we decided to post some angularJS articles from now on. At first, we’re coming up with a nifty minimal RSS Feed Reader with few lines of code. Demo View It Online Download Source Files You clicked the demo button, didn’t you ? […]

    Our beautiful designs open the door to a realm of limitless possibilities, where imagination knows no bounds.

    Features
    • Page builder
    • Theme options
    • Theme builder
    • Template library
    Resources
    • Support center
    • Documentation
    • Community
    • Hosting
    Follow us
    • Behance
    • Dribbble
    • Facebook
    • Instagram
    Get in touch
    • hello@company.com

    © Sierra WordPress Theme. All Rights Reserved.

    • Terms & Conditions
    • Privacy Policy