Skip to content

Commit 6f56ac0

Browse files
committed
Initial Commit
1 parent 61fc033 commit 6f56ac0

File tree

7 files changed

+324
-1
lines changed

7 files changed

+324
-1
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.DS_Store

README.md

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,58 @@
1-
# SimplerWeather
1+
# SimplerWeather
2+
3+
This is Simple weather plugin for jQuery which is based on [jQuery.simpleWeather](https://github.com/monkeecreate/jquery.simpleWeather) by [James Fleeting](https://twitter.com/fleetingftw). It updates the original library from using Yahoo's Weather API to instead use the [Dark Sky API](https://darksky.net/dev).
4+
5+
Here are a few differences to note before using this library:
6+
- Dark Sky requires an API key (see Usage for how to get a key).
7+
- Dark Sky includes less weather codes/icons than Yahoo Weather but may expand in the future.
8+
- Longitude and longitude are required instead of location names or IDs.
9+
- In general, a lot more data is provided by the Dark Sky API.
10+
11+
## Usage:
12+
13+
[Sign up over at Dark Sky](https://darksky.net/dev/register) is required to generate a Dark Sky API key. If more than 1000 requests per 24 hours are needed a payment method must also be entered. Once an API key has been obtained then the library can be used like:
14+
15+
```
16+
$.simplerWeather( {
17+
location: '40.785091,73.96828',
18+
apikey: 'YOUR_API_KEY',
19+
success: function( weather ) { ... },
20+
error: function( error ) { ... }
21+
```
22+
23+
See `example.js` for a full example. Please also note that when using this method your API key will be public. It is recommended that you use the proxy to hide your API key (see Proxy Example below)
24+
25+
### Dark Sky Attribution
26+
27+
Dark Sky requires a `powered by Dark Sky` link when using their data ([#](https://darksky.net/dev/docs/faq#attribution)). To help with this the `weather.attributionlink` key has been added to the data.
28+
29+
### Proxy Example:
30+
As Dark Sky requires an API key a `proxy.php` file is found in this repository which allows the API key to be hidden. To use the proxy set `authmethod` to `proxy` and then set `proxyurl` to the location of the `JSON` data.
31+
32+
```
33+
$.simplerWeather( {
34+
location: '40.785091,73.96828',
35+
authmethod: 'proxy',
36+
proxyurl: 'proxy.php',
37+
success: function( weather ) { ... },
38+
error: function( error ) { ... }
39+
```
40+
41+
By default `units` and `exclude` attributes are added to the Dark Sky request. When using the proxy the default GET request will look something like this: `https://example.com/proxy.php?lat=40.785091&lon=-73.968285&units=us`. To hide the latitude and longitude, modify the query in `simplerweather.js` and then set the location directly the proxy file.
42+
43+
While the example using `PHP` the JavaScript should support any URL which returns `JSON` output.
44+
45+
### GeoLocation
46+
47+
A `geolocation-example.js` is also included which can be used as a template to get site visitors weather location based the location provided by their browser. Note this isn't a full example but can be used as a starting place.
48+
49+
### Extending and Modifying the Script
50+
51+
Dark Sky has [API documentation](https://darksky.net/dev/docs) which can be used to modify this script. It was created for a simple use-case so does not include all weather data one may want to use.
52+
53+
## Getting Help:
54+
For the sake of transparency the script is provided here as-is in hopes that others find it useful. Currently, I have no plans to maintain (outside of security vulnerabilities ). I will try to help point people in the right direction where I can.
55+
56+
## Contributing:
57+
58+
Feel free to open a PR to contribute to this project!

example.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
$( document ).ready( function() {
2+
3+
$.simplerWeather( {
4+
location: '40.785091,73.96828',
5+
units: 'f',
6+
apikey: 'YOUR_API_KEY',
7+
success: function( weather ) {
8+
currentWeather = '<h2> <i class="icon ' + weather.icon +
9+
'"></i> ' +
10+
Math.round( weather.temp ) + '&deg;' + weather.unit.toUpperCase();
11+
12+
currentWeather += '<p> Currently: ' + weather.currently +
13+
'</p>';
14+
15+
$( "#weather" ).html( currentWeather );
16+
//return forcast to unordered list.
17+
forecast = '<ul>';
18+
// the first value in the array is the current date so set i to 1 to get future weather
19+
for( var i = 1; i < 4; i++ ) {
20+
forecast += '<li><i class="icon ' + weather.forecast[ i ].icon +
21+
'"></i>';
22+
forecast += weather.forecast[ i ].summary; + '</li>';
23+
}
24+
forecast += '</ul>';
25+
26+
$( "#forecast" ).html( forecast );
27+
},
28+
error: function( error ) {
29+
$( "#weather" ).html( '<p>' + error + '</p>' );
30+
}
31+
} ); //end main weather display
32+
} );

geolocation-example.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
$( document ).ready( function() {
2+
3+
/*
4+
* Does the browser support geolocation?
5+
* Wrap any geolocation link/feature in this function
6+
*/
7+
function supportGeolocation() {
8+
if( "geolocation" in navigator ) {
9+
console.log( 'Browser supports geoLocation ' );
10+
return true;
11+
} else {
12+
console.log( 'Browser does no support geoLocation ' );
13+
return false;
14+
}
15+
}
16+
17+
/*
18+
* Returns on successfully getting location
19+
*/
20+
function navigatorSuccess( position ) {
21+
loadWeather( position.coords.latitude + ',' + position.coords.longitude );
22+
}
23+
/*
24+
* Returns on error getting location
25+
* See all Error codes at: https://developer.mozilla.org/en-US/docs/Web/API/PositionError
26+
*/
27+
function navigatorFail( error ) {
28+
if( error.code == 2 ) {
29+
console.log( 'Browser failed to provide location.' );
30+
} else {
31+
//timeout or permission error
32+
console.log( 'Error getting location.' );
33+
34+
}
35+
}
36+
37+
/*
38+
* Load weather based on location data provided
39+
*/
40+
function loadWeather( location ) {
41+
$.simplerWeather( {
42+
location: location,
43+
apikey: 'YOUR_API_KEY',
44+
success: function( weather ) {
45+
geoLocationWeather = '<h2> <i class="icon ' + weather.icon +
46+
'"></i> ' + Math.round( weather.temp ) + '&deg;';
47+
geoLocationWeather +=
48+
'<p> Currently: </span>' + weather.currently + '</p>';
49+
50+
$( "#local_weather" ).html( geoLocationWeather );
51+
52+
},
53+
error: function( error ) {
54+
$( "#local_weather" ).html( '<p>' + error + '</p>' );
55+
}
56+
} );
57+
}
58+
} );

jquery.simplerWeather.js

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
/*! simplerWeather v1.0.0
2+
Author: Brooke.
3+
URL: https://github.com/BrookeDot/SimplerWeather
4+
License: MIT
5+
Based on SimpleWeather -- https://github.com/monkeecreate/jquery.simpleWeather
6+
7+
Simple Weather Java Switches to DarkSky */
8+
9+
( function( $ ) {
10+
'use strict';
11+
12+
function getAltTemp( unit, temp ) {
13+
if( unit === 'f' ) {
14+
return Math.round( ( 5.0 / 9.0 ) * ( temp - 32.0 ) );
15+
} else {
16+
return Math.round( ( 9.0 / 5.0 ) * temp + 32.0 );
17+
}
18+
}
19+
20+
$.extend( {
21+
simplerWeather: function( options ) {
22+
options = $.extend( {
23+
location: '',
24+
units: 'f',
25+
authmethod: 'apikey',
26+
apikey: '',
27+
proxyurl: '',
28+
forecast: 'true',
29+
forecastdays: '4',
30+
success: function( weather ) {},
31+
error: function( message ) {}
32+
}, options );
33+
34+
let location = '';
35+
36+
//Sets the units based on https://darksky.net/dev/docs
37+
if( options.units.toLowerCase() === 'c' ) {
38+
var units = 'si'
39+
} else {
40+
var units = 'us'
41+
}
42+
43+
//Check that the latitude and longitude has been set and generate the API URL based on authentication method
44+
function getWeatherURL( authmethod ) {
45+
if( /^\-?\d+(\.\d+)?,\s*\-?\d+(\.\d+)$/.test( options.location ) ) {
46+
47+
let geoLocation = options.location.split( ',' );
48+
var lat = geoLocation[ 0 ];
49+
var lon = geoLocation[ 1 ];
50+
} else {
51+
options.error(
52+
'Could not retrieve weather due to an invalid location. Must enter location as latitude,longitude'
53+
);
54+
}
55+
if( authmethod === "apikey" && options.apikey !== '' ) {
56+
let apiKey = encodeURIComponent( options.apikey );
57+
return 'https://api.darksky.net/forecast/' + apiKey + '/' +
58+
lat + ',' + lon + '/?units=' + units +
59+
'&exclude=minutely,hourly,alerts,flags';
60+
} else if( authmethod === "proxy" && options.proxyurl !== '' ) {
61+
return encodeURI( options.proxyurl + '?lat=' + lat + '&lon=' +
62+
lon + '&units=' + units );
63+
} else {
64+
options.error(
65+
'Could not retrieve weather due to an invalid api key or proxy setting.'
66+
);
67+
}
68+
}
69+
70+
$.getJSON(
71+
encodeURI( getWeatherURL( options.authmethod ) ),
72+
function( data ) {
73+
if( data !== null ) {
74+
var result = data,
75+
weather = {};
76+
77+
weather.temp = result.currently.temperature;
78+
weather.currently = result.currently.summary;
79+
weather.icon = result.currently.icon;
80+
weather.pressure = result.currently.pressure;
81+
weather.humidity = result.currently.humidity;
82+
weather.visibility = result.currently.visibility;
83+
weather.updated = result.currently.time;
84+
85+
weather.high = result.daily.data[ 0 ].temperatureHigh;
86+
weather.low = result.daily.data[ 0 ].temperatureLow;
87+
weather.sunrise = result.daily.data[ 0 ].sunriseTime;
88+
weather.sunset = result.daily.data[ 0 ].sunsetTime;
89+
weather.description = result.daily.data[ 0 ].summary;
90+
91+
weather.attributionlink = "https://darksky.net/";
92+
weather.unit = options.units.toLowerCase();
93+
94+
if( weather.unit === 'f' ) {
95+
weather.altunit = 'c';
96+
} else {
97+
weather.altunit = 'f';
98+
}
99+
100+
weather.alt = {
101+
temp: getAltTemp( options.units, weather.temp ),
102+
high: getAltTemp( options.unit, weather.high ),
103+
low: getAltTemp( options.unit, weather.low )
104+
};
105+
106+
if( options.forcast &&
107+
parseInt( options.forecastdays ) !== "NaN" ) {
108+
109+
weather.forecast = [];
110+
111+
for( var i = 0; i < options.forecastdays; i++ ) {
112+
var forecast = result.daily.data[ i ];
113+
forecast.date = forecast.time;
114+
forecast.summary = forecast.summary;
115+
forecast.high = forecast.temperatureHigh;
116+
forecast.low = forecast.temperatureLow;
117+
forecast.icon = forecast.icon;
118+
119+
120+
forecast.alt = {
121+
high: getAltTemp( options.units, forecast.temperatureHigh ),
122+
low: getAltTemp( options.units, forecast.temperatureLow )
123+
};
124+
125+
weather.forecast.push( forecast );
126+
}
127+
}
128+
options.success( weather );
129+
} else {
130+
options.error(
131+
'There was a problem retrieving the latest weather information.'
132+
);
133+
}
134+
}
135+
);
136+
return this;
137+
}
138+
} );
139+
} )( jQuery );

jquery.simplerWeather.min.js

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

proxy.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
// File Name: proxy.php
3+
4+
function get_http_response_code($url) {
5+
$headers = get_headers($url);
6+
return substr($headers[0], 9, 3);
7+
}
8+
9+
10+
$api_key = 'YOUR_API_KEY';
11+
$api_endpoint = 'https://api.darksky.net/forecast';
12+
13+
$lat = ( isset( $_GET[ 'lat' ] ) && is_numeric( $_GET[ 'lat' ] ) ? ( float )( $_GET[ 'lat' ] ) : null );
14+
$lon = ( isset( $_GET[ 'lon' ] ) && is_numeric( $_GET[ 'lon' ] ) ? ( float )( $_GET[ 'lon' ] ) : null );
15+
$units = ( isset( $_GET[ 'units' ] ) && strtolower( $_GET[ 'units' ] ) == 'si' ? 'si' : 'us' );
16+
17+
$api_url = $api_endpoint . '/' . $api_key . '/' . $lat . ',' . $lon . '/?units=' . $units . '&exclude=minutely,hourly,alerts,flags';
18+
if( ! isset ( $api_url ) ) { die( 'no api URL found' ); }
19+
if( get_http_response_code( $api_url ) !== '200' ){ die( 'URL format invalid' ); }
20+
21+
$api_data = file_get_contents( $api_url );
22+
23+
header('Content-type:application/json;charset=utf-8');
24+
echo ( $api_data ) ;

0 commit comments

Comments
 (0)