Saturday, 5 July 2014

Display location weather in Javascript

This is an example of a HTML/JS app to display the weather based on the current location using the public API from openweather.org. If the user denies permission to share the location, a dialog window will appear for the user to enter a postcode.

In my HTML file I have essentially two main div’s. One of the divs displays the current weather if the user accepts the Geolocation permissions, and the other div shows a dialog box if the user does not accept the Geolocation permissions.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Weather</title>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>

    <div class="container">
        
        <div class="weather"></div>
        
        <div class="noweather">
            <div class="postcodeContainer">  
                <p class="postcode-msg">Please enter postcode</p>
                <input type="text" class="postcodeText" id="postcode" placeholder="Postcode search" val=""/>
                <input type="submit" class="postcodeSubmit" value="Go" id="postcodeBtn"/>
                <p class="postcode-error">Invalid postcode</div>
            </div>
        </div>
        
    </div>

    <script src="js/ jquery-1.11.2.min.js"></script>
    <script src='js/main.js'></script>
</body>
</html>

The CSS file will display the weather in the centre of the screen with the ‘Roboto’ Google font. The styling for the postcode dialog box is also styled.

body {font-family: 'Roboto', sans-serif;}
p, input { padding: 0; margin: 0; }
.container { position: absolute; top: 50%; left: 50%; padding: 20px; }
.weather { position: relative; width: 600px; height: 200px; margin: -70px 0 0 -120px; display: none; }
.noweather { color: #999999; 
position: relative; display: none; width: 200px; height: 128px; height: 128px;
margin: -70px 0 0 -120px;
border: 4px solid #cccccc; 
-webkit-box-shadow: 1px 1px 3px 1px rgba(0,0,0,0.5); 
-moz-box-shadow: 1px 1px 3px 1px rgba(0,0,0,0.5);
box-shadow: 1px 1px 3px 1px rgba(0,0,0,0.5); }
.postcodeContainer {text-align: center;}
.postcode-msg { font-size: 14px; padding: 16px 0 10px 0; letter-spacing: 0px; }
.postcodeText { width: 170px; padding: 5px 0 5px 0px; margin-bottom: 2px; }
.postcodeSubmit { width: 174px; padding: 5px 0 5px 0; background: #000000; color: #ffffff; margin-bottom: 5px; border: none; }
.postcodeSubmit:hover {background: #999999;}
.postcode-error { color: #ff0000; font-size: 12px; display: none; }

In the main.js Javascript file, I firstly detect if the browser supports geolocation. If the geolocation is supported then I called the getWeather() function along with the current longitude and latitude to display the current weather. Conversely if the geolocation is not supported then I display the postcode dialog box, and use the isPostcodeValid() helper function to check if the postcode is valid. I will again reuse the getWeather() function along the postcode to display the current weather. Note, I have used the getWeather() function for both the geolocation and postcode options. I have a pass a parameter which can use either the geolocation or postcode API.

$(document).ready(function() {
    'use strict';
    
    var App = {
        geolocationStr:"http://api.openweathermap.org/data/2.5/weather?lat=",
        postcodeStr:"http://api.openweathermap.org/data/2.5/weather?zip=",
        init:function(){
            App.getLocation();
        },
        getLocation:function(){
                
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(App.geoSuccess, App.geoError);
            }else {
                 $('p').text('GeoLocation not supported').appendTo('body');
            }
            
        },
        geoSuccess:function(e){
            App.getWeather(App.geolocationStr+e.coords.latitude+"&lon="+e.coords.longitude);   
        },
        geoError:function(e){
         
            $('.noweather').show();
            
            $('#postcodeBtn').on('click', function(){
                
                var postCodeValue = $('#postcode').val();
            
                if(isPostcodeValid(postCodeValue)){
                    $('.postcode-error').hide();
                    $('.noweather').hide();
                    App.getWeather(App.postcodeStr+postCodeValue +",uk");  
                    
                }else{
                    $('.postcode-error').show();
                }
            })
            
        },
        getWeather:function(url){
            
            $.ajax({
                url: url,
                dataType: 'jsonp',
                jsonpCallback: 'jsonCallback',
                success: function (data) {   
                    $('.weather').show();
                    $('<h1>').text('The weather is ' + data.weather[0].main.toLowerCase()).appendTo('.weather');
                }});
        }
    }
    
    App.init();
    
});

function isPostcodeValid(postcode){
    var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}\s*([0-9][a-zA-z][a-zA-z]){1}$/;
    return regPostcode.test(postcode);
}

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP