Skip to content

Instantly share code, notes, and snippets.

@robhurring
Last active December 20, 2015 04:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robhurring/6074149 to your computer and use it in GitHub Desktop.
Save robhurring/6074149 to your computer and use it in GitHub Desktop.
Angular weather service using openweathermap.org -- not fully tested. (uses gist: https://gist.github.com/robhurring/6074128)
app.factory("WeatherService", ['$q', '$http', function($q, $http) {
var SERVICE_ENDPOINT = "http://api.openweathermap.org/data/2.5";
var JSON_P_SUFFIX = "&callback=JSON_CALLBACK"
var request = function(path) {
var deferred = $q.defer();
$http.jsonp(SERVICE_ENDPOINT + path + JSON_P_SUFFIX).
success(function(data, status, headers, config){
deferred.resolve(data);
}).
error(function(data, status, headers, config){
deferred.reject(data);
})
return deferred.promise;
};
var normalizeDays = function(days) {
var d = days;
if(days === undefined || days === null || parseInt(days) < 1) d = 7;
if(d > 14) d = 14; // max 14 days
return d;
};
return {
current: {
byPosition: function(lat, lng){
var path = "/weather?lat="+lat+"&lon="+lng;
return request(path);
},
byCity: function(cityName){
var path = "/weather?q="+cityName;
return request(path);
},
byCityId: function(cityId){
var path = "/weather?id="+cityId;
return request(path);
}
},
forecast: {
byPosition: function(lat, lng, days, units) {
var u = units || 'imperial'; // internal, metric, or imperial
var d = normalizeDays(days);
var path = "/forecast/daily?lat="+lat+"&lon="+lng+"&cnt="+d+"&mode=json";
return request(path);
},
byCity: function(cityName, days, units) {
var u = units || 'imperial'; // internal, metric, or imperial
var d = normalizeDays(days);
var path = "/forecast/daily?q="+cityName+"&cnt="+d+"&mode=json";
return request(path);
},
byCityId: function(cityId, days, units) {
var u = units || 'imperial'; // internal, metric, or imperial
var d = normalizeDays(days);
var path = "/forecast/daily?id="+cityId+"&cnt="+d+"&mode=json";
return request(path);
}
}
}
}]);
app.controller('MainCtrl', [
'$scope',
'GeolocationService',
'WeatherService',
function ($scope, $window, geolocation, weather){
$scope.position = null;
$scope.weather = null
$scope.forecast = null;
// SEE: https://gist.github.com/robhurring/6074128
geolocation().then(function(position) {
$scope.position = position;
});
$scope.$watch('position', function(position){
if(!position) return;
weather.current.byPosition(position.coords.latitude, position.coords.longitude).then(function(data){
$scope.weather = data;
});
weather.forecast.byPosition(position.coords.latitude, position.coords.longitude).then(function(data){
$scope.forecast = data;
});
});
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment