4

How do I get mu openweather API to work with geolocation? This is my current html code:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css">
        <link rel="stylesheet" href="main.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type='text/javascript' src='app.js'></script>
    </head>
    <body>
        <div class="jumbotron">
            <button onclick="getLocation()">Get my location.</button>
            <p id="demo"></p>

            <script>
                var x = document.getElementById("demo");
                function getLocation() {
                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(showPosition);
                    } else { 
                        x.innerHTML = "Geolocation is not supported by this browser.";
                    }
                }

                function showPosition(position) {
                    x.innerHTML = "Latitude: " + position.coords.latitude + 
                                  "<br>Longitude: " + position.coords.longitude;    
                }
            </script>

            <p>The weather outside is: </p> 
            <div class= "weather">
                Oops.. there is no temperature available for your location right now.
            </div>
        </div>                                  
    </body>
</html>

And my JavaScript code:

$(document).ready(function(){
    $.getJSON( "http://api.openweathermap.org/data/2.5/weather?q=Eindhoven&appid=9334f947893792dcb9b2e2c05ae23eb0", function( data ) {
        $('.weather').html(Math.round(data.main.temp-273)+ ' degrees Celcius');
    });

});

I got the weather in Eindhoven city working, but I want to be able to adjust it to the latitude and longitude. Can someone fix my code for me? And help me?

I know it has something to do with this link: api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon} but I don't know how to implement my own fount latitude and longitude in it...

Mantas Čekanauskas
  • 2,218
  • 6
  • 23
  • 43
Maris
  • 91
  • 1
  • 2
  • 10

2 Answers2

5

You can get data about the location with use third-party API, for example: http://ip-api.com/

var getIP = 'http://ip-api.com/json/';
$.getJSON(getIP).done(function(location) {
    console.log(location)
})

Next get WeatherData from OpenWeatherMap service using the ip-api that we got above

var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
    $.getJSON(openWeatherMap, {
        lat: location.lat,
        lon: location.lon,
        units: 'metric',
        appid: 'APIKEY'
    }).done(function(weather) {
        console.log(weather)
    })
})

In this case, the celsius temperature (metric)

Or using HTML5 Geolocation API (in Google Chrome work only with HTTPS or on localhost)

var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
if (window.navigator && window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(function(position) {
        $.getJSON(openWeatherMap, {
            lat: position.coords.latitude,
            lon: position.coords.longitude,
            units: 'metric',
            appid: 'APIKEY'
        }).done(function(weather) {
            console.log(weather)
        })
    })
}
Ali H. Kudeir
  • 756
  • 2
  • 9
  • 19
Mikhail
  • 11,067
  • 7
  • 28
  • 53
  • Thanks! This seems like a great answer, but it still isn't working. First of all get a current location of Friesland, and I'm not in Friesland. And second of all there is no weather. – Maris Nov 27 '15 at 08:59
  • @Maris ip-api shows to you, your location is Friesland but you don't in Friesland? I understand correctly? Ok. And second. I wrote in my answer that `$.getJSON(openWeatherMap, {` and `.done(function(weather) {` must be inside `$.getJSON(getIP).done(function(location) {})` – Mikhail Nov 27 '15 at 14:07
  • Yes that is correct. And I did that but it is not working. – Maris Nov 28 '15 at 07:10
0

Lets try it , I hope that is a better solution to get current weather via using geolacation and Openweather API . Simply pass your Openweather API Key , you will get a json array, fetch your location and current weather. And you also use your weather icon which you want.

window.addEventListener("load",() =>{
    let long;
    let lag;
    
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition((position) =>{
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        const proxy = "https://cors-anywhere.herokuapp.com/";
        const api = `${proxy}api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=9891731b361e47661f72b06213efbf65`;
        fetch(api) 
           .then((response) =>{
               return response.json();
           })
           .then(data =>{
               const {name} = data;
               const {feels_like} = data.main;
               const {id,main} = data.weather[0];
               loc.textContent = name;
               climate.textContent = main;
               tempValue.textContent = Math.round(feels_like-273);
               if(id < 250){
                   tempIcon.src = './icon/storm.svg'
               } 
               else if(id < 350){
                tempIcon.src = './icon/drizzle.svg'  
               }
               else if(id < 550){
                tempIcon.src = './icon/rain.svg'  
               }
               else if(id < 650){
                tempIcon.src = './icon/snow.svg'  
               }
               else if(id < 800){
                tempIcon.src = './icon/atmosphere.svg'  
               }
               else if(id === 800){
                tempIcon.src = './icon/clear.svg'  
               }
               else if(id >800){
                tempIcon.src = './icon/clouds.svg'  
               }
               console.log(data);
           })
        })  
    }
}) 
Devsaiful
  • 147
  • 4