Skip to content

Instantly share code, notes, and snippets.

@marchawkins
Last active July 29, 2021 02:28
Show Gist options
  • Save marchawkins/9755430 to your computer and use it in GitHub Desktop.
Save marchawkins/9755430 to your computer and use it in GitHub Desktop.
Using the OpenWeatherMap and Google's geolocation APIs to get the current weather for the user-specified location. The user inputs a location, which is geocoded using Google Maps API. Uses the OpenWeatherMap API ((http://openweathermap.org/)) to get the data. Data is returned in JSON format. Most major browsers supported, including IE9, Chrome, …
<div class="row">
<div class="col-md-2 col-sm-2 col-xs-2">
<p><button class="btn btn-primary btn-sm" id="get-weather-btn"><span>Get Weather</span></button></p>
</div><!-- .col -->
<div class="col-md-10 col-sm-10 col-xs-10">
<div class="panel panel-default">
<div class="panel-heading">Weather &amp; Location Response</div>
<div class="panel-body">
<p>Enter Address: <input id="address" type="text" class="form-control"/></p>
<p>Lat/Long: <input id="location-lat-long" type="text" class="form-control"/></p>
<p>Weather: <textarea id="weather" class="form-control"></textarea></p>
<div id="map-canvas" style="min-height: 400px;"></div>
</div>
</div>
</div><!-- .col -->
</div><!-- .row -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
"use strict";
var geocoder;
var map;
var latitude,longitude;
// setup initial map
function initialize() {
geocoder = new google.maps.Geocoder(); // create geocoder object
var latlng = new google.maps.LatLng(40.6700, -73.9400); // set default lat/long (new york city)
var mapOptions = { // options for map
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // create new map in the map-canvas div
}
// function to geocode an address and plot it on a map
function codeAddress(address) {
geocoder.geocode( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location["k"];
longitude = results[0].geometry.location["A"];
$("#location-lat-long").val("lat: "+latitude+" / longitude: "+longitude); // write lat/long to input field
getWeather(latitude,longitude); // get weather for returned lat/long
map.setCenter(results[0].geometry.location); // center the map on address
var marker = new google.maps.Marker({ // place a marker on the map at the address
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// function to get weather for an address
function getWeather(latitude,longitude) {
if(latitude != '' && longitude != '') {
$("#weather").val("Retrieving weather..."); // write temporary response while we get the weather
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&units=imperial", function(data) { // add '&units=imperial' to get U.S. measurements
var currWeather = new Array(); // create array to hold our weather response data
currWeather['currTemp'] = Math.round(data.main.temp); // current temperature
currWeather['highTemp'] = Math.round(data.main.temp_max); // today's high temp
currWeather['lowTemp'] = Math.round(data.main.temp_min); // today's low temp
currWeather['humidity'] = Math.round(data.main.humidity); // humidity (in percent)
currWeather['pressure'] = data.main.pressure * 0.02961339710085; // barometric pressure (converting hPa to inches)
currWeather['pressure'] = currWeather['pressure'].toFixed(2); // barometric pressure (rounded to 2 decimals)
currWeather['description'] = data.weather[0].description; // short text description (ie. rain, sunny, etc.)
currWeather['icon'] = "http://openweathermap.org/img/w/"+data.weather[0].icon+".png"; // 50x50 pixel png icon
currWeather['cloudiness'] = data.clouds.all; // cloud cover (in percent)
currWeather['windSpeed'] = Math.round(data.wind.speed); // wind speed
currWeather['windDegree'] = data.wind.deg; // wind direction (in degrees)
currWeather['windCompass'] = Math.round((currWeather['windDegree'] -11.25) / 22.5); // wind direction (compass value)
// array of direction (compass) names
var windNames = new Array("North","North Northeast","Northeast","East Northeast","East","East Southeast", "Southeast", "South Southeast","South","South Southwest","Southwest","West Southwest","West","West Northwest","Northwest","North Northwest");
// array of abbreviated (compass) names
var windShortNames = new Array("N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW");
currWeather['windDirection'] = windNames[currWeather['windCompass']]; // convert degrees and find wind direction name
var response = "Current Weather: "+currWeather['currTemp']+"\xB0 and "+currWeather['description'];
var spokenResponse = "It is currently "+currWeather['currTemp']+" degrees and "+currWeather['description'];
if(currWeather['windSpeed']>0) { // if there's wind, add a wind description to the response
response = response+" with winds out of the "+windNames[currWeather['windCompass']]+" at "+currWeather['windSpeed'];
spokenResponse = spokenResponse+" with winds out of the "+windNames[currWeather['windCompass']]+" at "+currWeather['windSpeed'];
if(currWeather['windSpeed']==1) {
response += " mile per hour";
spokenResponse += " mile per hour";
} else {
response += " miles per hour";
spokenResponse += " miles per hour";
}
}
console.log(data); // log weather data for reference (json format)
$("#weather").val(response); // write current weather to textarea
speakText(spokenResponse);
});
} else {
return false; // respond w/error if no address entered
}
}
// function to speak a response
function speakText(response) {
// setup synthesis
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[2]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; // 0 to 2
msg.text = response;
msg.lang = 'en-US';
speechSynthesis.speak(msg);
}
google.maps.event.addDomListener(window, 'load', initialize); // setup initial map
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // make sure we don't cache our JSON request
// get location button functionality
$("#get-weather-btn").click(function(event){
event.preventDefault();
$("#location-lat-long").val("Finding location. Please wait...");
var address = $("#address").val(); // grab the address from the input field
codeAddress(address); // geocode the address
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment