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 the Openweather API and display the current temperature of the city.
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:
- OpenWeatherMap.org account. It’s a quick signup .
- Node.js: Visit the official Node.js website to download and install Node, if you haven’t already. If you want to know, what is a node, how to install, check here my previous post? Why Node.js is favourite among developers.
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 [email protected]. --save
Create a new folder inside your project directory give a name as “geocode” and add file gecode.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.js file 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 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
认真拜读,好为学徒!
It’s a pity you don’t have a donate button! I’d certainly donate to this excellent blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this site with my Facebook group. Chat soon!
Well I sincerely liked studying it. This article procured by you is very helpful for proper planning.
Appreciating the hard work you put into your site and in depth information you provide.
It’s awesome to come across a blog every once in a while that isn’t the same out
of date rehashed material. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.
Thank for your comment.Please download our Android app for update post https://goo.gl/F8U3z7
You should be a part of a contest for one of the finest sites on the net.
I will recommend this site!
Wow, this paragraph is nice, my younger sister is analyzing such things, so I am going to inform
her.
Magnificent beat ! I wish to apprentice while you amend your site, how
can i subscribe for a blog site? The account aided me a acceptable deal.
I had been tiny bit acquainted of this your broadcast offered bright clear concept
Excellent site you’ve got here.. It’s difficult to find quality
writing like yours these days. I truly appreciate
people like you! Take care!!
Hi, I think your website might be having browser compatibility
issues. When I look at your website in Opera, it looks fine but when opening
in Internet Explorer, it has some overlapping. I just wanted to give you
a quick heads up! Other then that, great blog!
It’s really very complex in this active life to listen news on TV,
therefore I only use web for that purpose, and get the
newest news.
I’m not sure why but this website is loading extremely slow
for me. Is anyone else having this problem or is it a problem on my end?
I’ll check back later on and see if the problem still exists.
Aw, this was an incredibly nice post. Spending some
time and actual effort to create a very good article…
but what can I say… I hesitate a lot and don’t manage to get anything
done.
Wow, that’s what I was exploring for, what a stuff! present here at this blog, thanks
admin of this website.
I was curious if you ever thought of changing the structure of
your site? Its very well written; I love what youve got to say.
But maybe you could a little more in the way of content so people could connect
with it better. Youve got an awful lot of text for only having 1 or two images.
Maybe you could space it out better?
Great information. Lucky me I discovered your site by chance (stumbleupon).
I have bookmarked it for later!
Incredible points. Great arguments. Keep up the great
spirit.
I used to be suggested this web site by way of my cousin. I’m now not
positive whether this put up is written by him as nobody else realize such certain approximately my trouble.
You’re wonderful! Thank you!
Hi! I just wanted to ask if you ever have any issues with
hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due
to no backup. Do you have any solutions to
prevent hackers?
Usually I do not read post on blogs, but I would like to say that this write-up very forced me to take
a look at and do it! Your writing taste has been surprised me.
Thanks, very nice article.
Hello my friend! I want to say that this article is awesome, nice written and
come with almost all important infos. I’d like to peer
extra posts like this .
This website was… how do I say it? Relevant!! Finally I’ve found something that helped
me. Cheers!
I have been exploring for a little for any high quality articles or blog posts in this
sort of space . Exploring in Yahoo I ultimately stumbled upon this site.
Studying this info So i’m glad to exhibit that I have a very just right uncanny feeling I discovered just what I needed.
I most certainly will make certain to don?t disregard this website and provides
it a glance on a continuing basis.
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! By the way, how can we communicate?
Good post. I absolutely appreciate this website.
Continue the good work!
Hi i am kavin, its my first time to commenting anyplace, when i read this piece
of writing i thought i could also make comment due to this sensible
piece of writing.
Hey There. I found your blog using msn. This is a
very well written article. I’ll make sure to bookmark it and come back to read more
of your useful information. Thanks for the post.
I will definitely comeback.
I feel this is one of the so much significant information for me.
And i’m glad studying your article. However want to statement on few normal issues, The website taste is great, the
articles is truly great : D. Good task, cheers
I’m not that much of a online reader to be honest but your blogs really nice,
keep it up! I’ll go ahead and bookmark your site
to come back down the road. Many thanks
Hey! I just wanted to ask if you ever have any problems with hackers?
My last blog (wordpress) was hacked and I ended up losing
several weeks of hard work due to no back up.
Do you have any solutions to stop hackers?
I’m really loving the theme/design of your web site.
Do you ever run into any browser compatibility issues?
A small number of my blog visitors have complained about my site not operating correctly in Explorer but looks great in Firefox.
Do you have any ideas to help fix this issue?
Wow, that’s what I was exploring for, what a material!
present here at this web site, thanks admin of this website.
Great blog here! Also your web site loads up fast! What web host
are you using? Can I get your affiliate link to your host?
I wish my website loaded up as fast as yours lol
Pretty nice post. I just stumbled upon your weblog and wanted to mention that I’ve really loved browsing your weblog posts.
In any case I’ll be subscribing to your rss feed and I am hoping you write again very soon!
I’ll immediately grab your rss as I can not
find your email subscription link or newsletter service.
Do you have any? Kindly allow me realize in order that I may subscribe.
Thanks.
I am truly glad to read this website posts which carries lots of helpful data, thanks for providing these statistics.
Thanks a lot for sharing this with all people you really
recognize what you’re talking approximately!
Bookmarked. Kindly also consult with my site =).
We could have a link trade agreement between us
Thanks for some other fantastic article. The place else may anybody
get that type of info in such a perfect manner of writing?
I’ve a presentation subsequent week, and I’m at the look
for such information.
I am truly thankful to the owner of this web site who has shared
this impressive article at at this place.
What’s up to all, how is the whole thing, I think every one
is getting more from this web site, and your views are nice for new
visitors.
Excellent post. I was checking constantly this blog and I am inspired!
Very helpful info specifically the closing phase 🙂 I maintain such
information a lot. I used to be looking for this certain info for a
very lengthy time. Thanks and good luck.
It’s very easy to find out any matter on web as compared to books,
as I found this piece of writing at this website.