How To Get Current Weather Data

In this article, I’m gonna explain, how can we get the current weather data. To get current weather data, I will use OpenWeatherMap API. So let’s start it.

First of all, you need to create an account on openweathermap.org so that you can get your API keys.

Get API Keys

1) Create an account here(https://home.openweathermap.org/users/sign_up)
2) You can get your API keys here. (https://home.openweathermap.org/api_keys)

View:

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Weather API</h1>
    <p class="lead">Get Current Weather Data</p>
    <p><a href="JavaScript:void(0)" id="GetData" class="btn btn-primary btn-lg">Get Data &raquo;</a></p>
</div>
<div class="row">
    <div class="col-lg-12">
        <div id="WeatherData">

        </div>
    </div>
</div>

Script:

<script>
        var latitude, longitude;
        $('#GetData').click(function () {
            debugger
            getLocation();
            setTimeout(function () {
                debugger
                if (!IsNullOrEmpty(latitude) && !IsNullOrEmpty(longitude)) {
                    $.ajax({
                        type: "POST",
                        url: "/Home/GetCurrentWeatherData",
                        data: { latitude: latitude, longitude: longitude },
                        success: function (res) {
                            if (!IsNullOrEmpty(res)) {
                                $('#WeatherData').empty().html(res);
                            }
                            else {
                                alert("Something went wrong");
                            }
                        },
                        error: function (e) {
                            alert("Something went wrong");
                            console.log(e);
                        }
                    })
                }
                else {
                    alert("Not able the find your current Geolocation.");
                }
            }, 100);
        });

        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(setCordinates);
            } else {
                alert("Geolocation is not supported by this browser.");
            }
        }

        function setCordinates(position) {
            latitude = position.coords.latitude;
            longitude = position.coords.longitude;
        }

        function IsNullOrEmpty(value) {
            if (value == null || value == undefined || $.trim(value) == 'undefined' || $.trim(value) == '') {
                return true;
            }
            return false;
        }
    </script>

In js, I’m handling the one-click event of a get data button. We need to pass our latitude and longitude to the API to get current weather data. So here I’m getting the lat long by calling the getLocation() function. Once I got the lat & long, I’m passing them to ajax call. In the response to the Ajax call, I will get an HTML string that I’m displaying in a div.

Controller

public ActionResult Index()
        {
            return View();
        }

        public string GetCurrentWeatherData(string latitude, string longitude)
        {
            try
            {
                string result = string.Empty;
                string WeatherAPIKey = "YOUR_API_KEY";
                string ParentURL = "https://api.openweathermap.org/data/2.5/weather?";
                string url = "lat=" + latitude + "&lon=" + longitude + "&appid=" + WeatherAPIKey + "&units=metric&mode=html";
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(ParentURL + url);
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Method = "GET";
                httpWebRequest.Accept = "application/json; charset=utf-8";
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (httpResponse.StatusCode == HttpStatusCode.OK || httpResponse.StatusCode == HttpStatusCode.Created)
                {
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        result = streamReader.ReadToEnd();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

The GetCurrentWeatherData() is a method that will call the API and return the HTML string. lat, long, and appid are required parameters for the API. We need to pass them compulsory. I’m passing 2 more like units and mode.

Parameter Description:

  • lat, long: It’s a Geographical coordinate. These 2 are required parameters.
  • appid: It’s an API key. (required parameter)
  • units: This is an optional parameter. It’s a unit of measurement. There are 3 types of units available standard, metric and imperial. If you don’t pass the unit parameter then by default it will consider a standard unit. You can check here(https://openweathermap.org/current#data) for more details.
  • mode: It is also an optional parameter. It is used to define the type of response(xml and html). If you don’t pass this parameter then the response will come in JSON format. Check more detail here(https://openweathermap.org/current#format)

Output

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories