jQM - Dynamically Populate Weather Data from JSON
by Dragan Gaić
HTML
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="b" data-role="header">
<h3>
City Search
</h3>
</div>
<div data-role="content">
<div class="example-wrapper" data-iscroll>
<input name="city-search" id="city-search" value="" type="text" placeholder="Enter City Name"/>
<a href="#" class="ui-btn" id="city-search-btn">Search</a>
</div>
</div>
</div>
</body>
</html>
CSS
.ui-content {
padding: 0 !important;
margin: 0 !important;
position : absolute !important;
top : 42px !important;
right : 0;
bottom : 0 !important;
left : 0 !important;
}
.info-window {
width: 180px;
height: 180px;
}
.icon-holder, info-holder {
float: left;
width: 50%;
height: 100%;
}
.info-text {
font-weight: bold;
}
JavaScript
$(document).on('pageinit', '#index', function(){
$(document).on('click', '#city-search-btn', function(){
var cityName = $('#city-search').val();
if(cityName.length > 0) {
var url = 'http://api.openweathermap.org/data/2.5/weather?q='+cityName+'&units=metric';
$.ajax({
url: url,
dataType: "jsonp",
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show', {theme:"a", text:"Please wait...", textonly:false, textVisible: true}); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide ajax spinner
},
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please enter city name!');
}
});
});
$(document).on('pagehide', '#map', function(){
$(this).remove();
});
$(document).on('pageshow', '#map',function(e,data){
var minZoomLevel = 12;
var myLatLng = new google.maps.LatLng(weatherData.response.coord.lat, weatherData.response.coord.lon);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var image = {
url: 'http://openweathermap.org/img/w/'+weatherData.response.weather[0].icon+'.png'
};
infoWindow = new google.maps.InfoWindow();
infoWindow.setOptions({
...