Wednesday, April 6, 2016

How to find city weather dynamically from Google map and Yahoo weather API with JavaScript

Hi There,


If you have read my post How to get city weather from Yahoo Weather API using Javascript and How to get city name against google map latitude and longitude using javascript then it would be probably more easy for you to get the required stuff.

We'll get city name from Google Map GeoLocation and weather status from Yahoo Weather JavaScript API call. Below is sample example code for this combined. You can Google around to get more information about these API's.

JavaScript Code:

[code]var Wcity;// = "Gilgit"; var yahooWeatherAPI; var GoogleAPI; $(document).ready(function () { GetLocation(); }); function GetLocation() { navigator.geolocation.watchPosition(callback); } function callback(position) { GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&key=AIzaSyAswpJn5_eL3fmsnFocNmiSsgXVog3CsH8"; //Fetching City Name $.getJSON(GoogleAPI, function (json) { if (Wcity == undefined) { Wcity = json.results[0].address_components[3].short_name; //alert(json.results[0].formatted_address); } ///Fetching Weather Report yahooWeatherAPI = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + Wcity + "%2C%20PK%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"; $.getJSON(yahooWeatherAPI, function (json) { var temp = Math.round((((json.query.results.channel.item.condition.temp - 32) * 5) / 9));// + "°"; $('#currentWeather').text(temp); $('#weatherCity').text(Wcity); }); } });[/code]

HTML Code:

[code] [/code]

Happy Coding :) 

No comments:

Post a Comment