JSFiddle - React, Tailwind, and code Playground
by Ty
HTML
<input type="text" id="cityName" />
<button id="getWeather">Get Weather</button>
<div id="map-canvas"></div>
CSS
#map-canvas {
height: 300px;
width: 500px;
}
JavaScript
/ When the document's loaded:
$(document).ready(function () {
/ / When the user clicks the button, get the input data
$('#getWeather').click(function () {
var city = $('#cityName').val();
// Make a call to the openweather API to get the data for the location the user gave us
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=imperial',
success: function (theWeather) {
// Get the proper temperature value for the data
console.log(theWeather);
var currentTemp = theWeather.main.temp;
// Create Google map
var mapOptions = {
center: new google.maps.LatLng(theWeather.coord.lat, theWeather.coord.lon),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"),
mapOptions);
// Add marker on the map
// Hovering on marker should show the temp
var marker = new google.maps.Marker({
map: map,
position: mapOptions.center,
title: currentTemp
});
// Clicking on the marker should show all weather data
var weatherData = 'Temperature: ' + currentTemp + '<br>' +
'Wind: ' + theWeather.wind.speed + '<br>' +
'Humidity: ' + theWeather.main.humidity + '<br>' +
'Cloud Coverage: ' + theWeather.clouds.all;
var infoWindow = new google.maps.InfoWindow({
content: weatherData
});
google.maps.event.addDomListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
});
});
});