BUILD A WEATHER WEBSITE WITH NODE.JS + EXPRESS + GOOGLEMAP + OPENWEATHERMAP

Zayed Rais
Sep 8, 2018 · 5 min read
weather — image via unsplash.com

In this tutorial you’ll learn, how to make call Google maps API to get the latitude and longitude of the city and pass to its Openweather API then will get the current temperature.

Here we are making a web app, where users can type in a city name and get real-time weather data instantly displayed on their screen.

All of the code for this project can be found in the GitHub Repo

Before going to this tutorial, we need pre-setup for the project build.

Live project Demo here Weather App

File structure look like-

|WeatherApp
|--WeatherApi
|--getWeather.js
|--geocode
|--geocode.js
|--public
|--js
|--postrequest.js
|--views
|--index.html
|--app.js
|--package.json

Pre-Project Setup

Here’s what you’ll need:

Step 1: OpenWeatherMap

if you want to play with APIs, OpenWeatherMap is a good place to start. They actually provide 11 different APIs all related to weather that you can access.

For this project, we are using the Free ‘Current Weather’ API. go to this link and sign up for an account.

Once signed in, select the API keys tab. Here you can Create a Key on the right-hand side of the page. Enter a name anything works and select Generate. Your API Key will appear on the left. Copy this key for later.

Now go to the API tab to know the details knowledge of API, and select API doc of the current weather data. and come to “By geographic coordinates” section, see once how API will show the data.

Step 2: Setting up the project

  • Create an empty directory named WeatherApp and run:
npm init
  • Fill out the required information to initialize the project.
  • Create a file named app.js — this file will have the main code for our application.

Building the API call

To make our API call, we’ll be using a popular npm module called request. the request has millions of downloads and is a module that simplifies the code needed to make an HTTP request in a node.

Install request by running:

npm install request --save

Now have to install express npm module.

Express.js is a web application framework for Node.js. It provides various features that make web application development fast and easy.

npm install express --save

If you want to install the latest version of a module of npm.

npm install Modulename@VerionNo. --save

Create a new folder inside your project directory give a name as “geocode” and add filegecode.js and add below code here.

const request = require('request'); 
var geocodeAddress =(address,callback) => {
var encodeAddress = encodeURIComponent(address);
request ({
url:`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeAddress}`,
json:true
},(error,response,body)=> {
if(error)
{
callback('Unable to conncet google Servers');
}
else if(body.status === 'ZERO_RESULTS')
{
callback('Unable to find address');
}
else if(body.status === 'OK')
{
callback(undefined,{
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
});
}
});
}
module.exports.getAddress = geocodeAddress;

Create a new folder inside your project directory as “WeatherApi” and add file getWeather.jsfile and add below code here.

////weather api call
const request =require('request');
var getWeather = (lat,lon,callback) => {
request ({
url: ​https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=KEYID`,
json: true
},(error,response,body)=>
{
if(!error && response.statusCode === 200)
{
callback(undefined,{
Temp: body.main.temp
});
}
else {
callback('unable to fetch weather');
}
});
};
module.exports.getWeather = getWeather;
////

The above code has to paste your key which is copied from Openweather API key

https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=KEYID

and KEYID replaced by your API KeyID.

Now create a new folder for “view” to type the city name and get the current weather data and add file index.html and add below code here.

<!DOCTYPE html> 
<html lang="en">
<head>
<title>Weather</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="/js/postrequest.js"></script>
</head>
<body>
<div class="container">
<div class="col-sm-4">
<h3>Search Weather</h3>
<div>
<form id="weatherForm">
<div class="form-group">
<label for="cityname">City Name:</label>
<input type="text" class="form-control" id="cityname" placeholder="Enter City Name for weather" />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div id="postResultDiv">
</div>
<br>
</div>
</div>
</div>
</body>
</html>

For this project, we are using an AJAX post method to display the temperature of the city. create new folder “public “and add new folder JS and add new file name as postrequest.js. and add the below code here.

$(document).ready(function () { 
// SUBMIT FORM
$("#weatherForm").submit( (event) => {
// Prevent the form from submitting via the browser.
event.preventDefault();
ajaxPost();
});
function ajaxPost() {
// PREPARE FORM DATA
var formData = {
cityname: $("#cityname").val(),
}
// DO POST
$.ajax({
type: "POST",
contentType: "application/json",
url: window.location + "api/customers/save",
data: JSON.stringify(formData),
dataType: 'json',
success: (output)=> {
$("#postResultDiv").html("<p>" +
"<br>" +
"" + JSON.stringify(`<code> ${output.addname} </code> Current Tempeature is <code>${output.temp}<sup>o</sup>C </code>`) + "</p>");
},
error: (e) => {
alert("Error!");
console.log("ERROR: ", e);
}
});
// Reset FormData after Posting
resetData();
}
function resetData() {
$("#citytname").val("");
}
})

Run your code

Now app is ready for a run.

Type the below code for a run the app from project root directory

node app.js

Now open your browser and visit:- localhost:8081, type a city name into the field and hit submit! You would see the current temperature of the city.

http://localhost:8081/

App demo: Live Weather App site

All of the code for this project can be found in the GitHub Repo

Alternative source: Tecoquest

Zayed Rais

Written by

I'm passionate about tech geeks. connect me on zayedrais@gmail.com

Tecoquest

Tecoquest

Tecoquest are the set of new techie articles, there you can boost your knowledge.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade