【问题标题】:Detect a geolocation with googleapis and receive current weather for this location from openweathermap with jQuery使用 googleapis 检测地理位置并使用 jQuery 从 openweathermap 接收该位置的当前天气
【发布时间】:2017-01-16 23:11:01
【问题描述】:

使用 googleapis 检测地理位置并使用 jQuery 从 openweathermap 接收该位置的当前天气

我正在尝试获取当前位置并获取该位置的当前天气。

这是我的 jQuery:

$(document).ready(function(){

    function getCity(position) {


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

            var url =  "https://maps.googleapis.com/maps/api/geocode/json? latlng=" +   position.coords.latitude + "," + position.coords.longitude;

            var city,
            country;
            $.getJSON(url, function(response) {
               city =  response.results[0].address_components[2].short_name;
               country = response.results[0].address_components[5].short_name;
               $('.yourLocationGoesHere').attr('value', city + ", " + country);
                });

                // Get weather by your location
                var celsius, fahrenheit, iconCode, iconUrl; 


             $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + city +  "&APPID=7f5806c8f3fd28b03e2d6580a50732d6", function (data) {

               celsius = Math.round(data.main.temp - 273.15);
               fahrenheit = Math.round(9/5 * (data.main.temp - 273) + 32);
               iconCode = data.weather[0].icon;
               iconUrl = "http://openweathermap.org/img/w/" + iconCode + ".png";
               $(".icon").html("<img src='" + iconUrl + "'>");

               $(':radio').change(function(){ 
                 // "this" will be the checked radio element       
                 if (this.id === 'celsius'){
                    $(".showDegree").html(celsius + "&degC");
                 }else{ 
                    $(".showDegree").html(fahrenheit + "&degF");
                    }
                 });

               });
              }
            });

我做错了什么。请帮忙。

【问题讨论】:

  • iconUrl 仅在$.getJSON() 回调中作用域,并且不能在该回调之外访问。查看抛出的错误 "iconUrl is undefined"
  • $.getJSON("api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=7f5806c8f3fd28b03e2d6580a50732d6", 函数(数据){ var celsius = Math.round(data.main.temp - 273.15); var fahrenheit = Math.round(9/5 * (data.main.temp - 273) + 32); var iconCode = data.weather[0].icon; var iconUrl = "openweathermap.org/img/w" + iconCode + ".png"; $ (".icon").html(""); });
  • @charlietfl 你能提供更多建议吗?

标签: javascript jquery json api geolocation


【解决方案1】:

你去吧:

$(document).ready(function(){



      //Check geolocation success 
      if (navigator.geolocation) {
        console.log('Geolocation API success') 

        // Geolocation API not supported by current browser
        }  else {
           console.log('Geolocation API is not supported by your browser')
           };
        });

        // Get latitude and longitude
        navigator.geolocation.getCurrentPosition(function(position){
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        console.log("Your latitude is: " + lat + " and your longitude is: " + long);

        // Get formatted address using reverse geocoding for latitude/longitude 
        $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long +  '&key=AIzaSyCJw0QfJXXleECtFD5031OMG75lZMiC6dY',                 function(response){
         $('.yourLocationGoesHere').text(response.results[7].formatted_address);
           })

           $.getJSON('',)
});

【讨论】:

    【解决方案2】:

    您必须始终注意变量的可用性。如果您在(回调)函数中定义它们,您将无法在它之外访问它们(我的意思是celsius fahrenheit iconCodeiconUrl)。

    因此,您可以在函数之前定义它们,就像对 citycountry 所做的那样,或者将使用它们的代码放在同一个函数中。

    另外请记住,如果您选择第一种解决方案,回调函数会在服务器响应后执行,这需要一些时间,因此无论如何变量都不会立即可用。所以在这种情况下,你应该在回调函数中处理传入的数据。

    【讨论】:

    【解决方案3】:

    让我们试试吧,我希望这是一个更好的解决方案,通过使用 geolacation 和 Openweather API 来获取当前天气。只需传递您的 OpenWeather API 密钥,您将获得一个 JSON 数组,获取您的位置和当前天气。您还可以使用您想要的天气图标。

    let loc = document.getElementById("location");
    let tempIcon = document.getElementById("temp-icon")
    let tempValue = document.getElementById("temp-value");
    let tempUnit = document.getElementById("temp-unit");
    let climate = document.getElementById("climate");
    let iconFile; 
    window.addEventListener("load", () => {
      let long;
      let lat;
    
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          long = position.coords.longitude;
          lat = position.coords.latitude;
          const proxy = "https://cors-anywhere.herokuapp.com/";
          const api = `${proxy}http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=Your OpenWeather API KEy`;
          fetch(api)
            .then((response) => {
              return response.json();
            })
            .then((data) => {
              console.log(data);
              const { name } = data;
              const { feels_like, temp, temp_max, temp_min } = data.main;
              const { id, icon, main } = data.weather[0];
              tempValue.textContent = Math.round(feels_like - 273);
              loc.textContent = name;
              climate.textContent = main;
              if (id<250){
                tempIcon.src = './icons/storm.svg' ;
              }
              else if (id<350){
                tempIcon.src = './icons/drizzle.svg' ;
              }
              else if (id<550){
                tempIcon.src = './icons/rain.svg' ;
              }
              else if (id<650){
                tempIcon.src = './icons/snow.svg' ;
              }
              else if (id<800){
                tempIcon.src = './icons/atmosphere.svg' ;
              }
              else if (id===800){
                tempIcon.src = './icons/sun.svg' ;
              }
              else if(id>800){
                tempIcon.src = './icons/clouds.svg' ;
              }
              console.log(
                Math.round(temp - 273),
                Math.round(temp_max - 273),
                Math.round(temp_min - 273)
              );
              console.log(name);
            });
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 2013-03-03
      • 2011-10-19
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      相关资源
      最近更新 更多