2017-02-22 25 views
0

Я создаю приложение Local Weather, и я создал раскрывающееся меню, в котором вы нажимаете на местоположение, и появляется информация, такая как Город, Страна и температура. Тем не менее, я не мог отображать информацию каждый раз, когда я нажимаю на местоположение.Как я могу получить информацию о стране в раскрывающемся меню в приложении Local Weather?

Вот мой код.

Как вы можете видеть, мне удалось загрузить текущее местоположение и температуру. Я сделал список глобальных переменных и позвонил в function getLocation() и запустил информацию в function getWeather(). В раскрывающемся меню я сделал массив с именем mainCities и добавлю города в раскрывающееся меню в function testMenu(). В этой функции я добавил onclick=testWeather('place'). Для этого я создал другую функцию под названием function testWeather(cityLocation), в которой я снова перечислил информацию для глобальных переменных и попытался запустить ее снова в function getWeather(), но она не работает. Что я упустил?

Вы можете увидеть мой код в действии: http://codepen.io/kikibres/pen/EZMJZw

$(document).ready(function() { 
 
    
 
    var currentLat; 
 
    var currentLong; 
 
    var currentCity; 
 
    var currentRegion; 
 
    var currentCountry; 
 
    
 
    var mainCities = { 
 
    'San_Francisco': { 
 
     'region': 'California', 
 
     'country': "United States", 
 
     'lat': 37.7749300, 
 
     'lon': -122.4194200 
 
    }, 
 
    'St._Louis': { 
 
     'region': 'Missouri', 
 
     'country': "United States", 
 
     'lat': 38.6272700, 
 
     'lon': -90.1978900 
 
    }, 
 
    'Miami': { 
 
     'region': 'Florida', 
 
     'country': "United States", 
 
     'lat': 25.7742700, 
 
     'lon': -80.1936600 
 
    }, 
 
    'Tokyo': { 
 
     'region': 'Tokyo', 
 
     'country': "Japan", 
 
     'lat': 35.689500, 
 
     'lon': 139.6917100 
 
    } 
 
    }; 
 
    
 
    function testMenu() { 
 
    for (var place in mainCities) { 
 
     var city = place.replace(/_/g, ' '); 
 
     $('#testMenu').append("<li onclick=testWeather('" + place + "');><a href='#'>" + city + "</a></li>"); 
 
    } 
 
    }; 
 
    
 
    function testWeather(cityLocation) { 
 
    currentLat = testLocation[cityLocation].lat; 
 
    currentLong = testLocation[cityLocation].lon; 
 
    currentRegion = testLocation[cityLocation].region; 
 
    currentCity = testLocation[cityLocation]; 
 
    currentCountry = testLocation[cityLocation].country; 
 
    
 
    getWeather(); 
 
    
 
    }; 
 
    
 
    function getLocation() { 
 
    $.getJSON('http://ip-api.com/json/?callback=?', function(data) { 
 
     
 
     currentRegion = data.regionName; 
 
     currentCity = data.city; 
 
     currentCountry = data.country; 
 
     currentLat = data.lat; 
 
     currentLong = data.lon; 
 
     
 
     //$("#cityname").text(currentCity); 
 
     
 
     getWeather(); 
 
     
 
    }); 
 
    }; 
 
    
 
function getWeather() { 
 
    
 
    $("#cityname").text(currentCity); 
 
    $("#state").text(currentRegion); 
 
    $("#country").text(currentCountry); 
 
    
 
    $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + currentLat + '&lon=' + currentLong + '&units=imperial&APPID=e656b9ee098cf2341fcfdb365b96b4a8', function(json) { 
 
    
 
    var showfahrenheit = true; 
 
    var tempfahrenheit = Math.round(json.main.temp); 
 
    var temcelcius = Math.round((tempfahrenheit - 32) * 5/9); 
 
    
 
    $("#temp").html(tempfahrenheit); 
 
    
 
    $('#unit-switch').on('click', function() { 
 
     if (showfahrenheit === false) { 
 
     $("#temp").html(tempfahrenheit); 
 
     showfahrenheit = true; 
 
     } else { 
 
     $("#temp").html(temcelcius); 
 
     showfahrenheit = false; 
 
     } 
 
     
 
     $("#unit-toggle").toggleClass("toggle"); 
 
\t \t \t //$('#temp').toggleClass('toggle'); 
 
    }); 
 
    
 
    }); 
 
}; 
 
    
 
    $(".cityarea").html(getLocation); 
 
    testMenu(); 
 
    
 
    
 
});
@import url('https://fonts.googleapis.com/css?family=Roboto:300,400'); 
 
body { 
 
    position: relative; 
 
} 
 
html,body{ 
 
    height:100%; 
 
} 
 
.wrapper { 
 
    width: 100%; 
 
    height: 100%; 
 
    position: relative; 
 
} 
 
.container { 
 
    position: relative; 
 
    display: block; 
 
    margin: 0 auto; 
 
    width: 60%; 
 
} 
 
.header h1 { 
 
    text-align: center; 
 
    font-family: 'Roboto', sans-serif; 
 
    font-weight: normal; 
 
    margin: 0 0 10px 0; 
 
} 
 
.weatherbox { 
 
    text-align: center; 
 
} 
 
.cityarea h2 { 
 
    color: #000000; 
 
    font-family: 'Roboto', sans-serif; 
 
    font-weight: normal; 
 
    font-size: 2em; 
 
    margin: 0; 
 
} 
 
.countryarea { 
 
    position: relative; 
 
    display: -webkit-flex; 
 
    display: flex; 
 
    -webkit-justify-content: center; 
 
    justify-content:   center; 
 
    margin: 0 auto; 
 
} 
 
.countryarea h3 { 
 
    margin: 0 0 10px 0; 
 
    font-family: 'Roboto', sans-serif; 
 
    font-weight: normal; 
 
} 
 
.countryarea h3:first-child { 
 
    margin-right: 8px; 
 
} 
 
.dropdown { 
 
    position: relative; 
 
    display: inline-block; 
 
    font-size: 16px; 
 
    color: #FFF; 
 
} 
 
.dropdown-header { 
 
    display: block; 
 
    padding: 3px 20px; 
 
    font-size: 12px; 
 
    line-height: 1.42857143; 
 
    color: #777; 
 
    white-space: nowrap; 
 
    text-transform: uppercase; 
 
} 
 
input[type=checkbox]{ 
 
    display: none; 
 
} 
 
label{ 
 
    box-sizing: border-box; 
 
    display: inline-block; 
 
    width: 100%; 
 
    background-color: #57A0D4; 
 
    padding: 10px 20px; 
 
    cursor: pointer; 
 
    text-align: center; 
 
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); 
 
    border-radius: 5px; 
 
    font-size: 20px; 
 
    -webkit-user-select: none; 
 
    -moz-user-select: none; 
 
    -ms-user-select: none; 
 
    user-select: none; 
 
} 
 
label .fa-globe { 
 
    margin-right: 10px; 
 
} 
 
/* The ul will have display:none by default */ 
 
ul{ 
 
    position: absolute; 
 
    list-style: none; 
 
    text-align: left; 
 
    width: 100%; 
 
    min-width: 160px; 
 
    z-index: 1; 
 
    padding: 5px 0; 
 
    margin: 2px 0 0; 
 
    font-size: 14px; 
 
    text-align: left; 
 
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2); 
 
    display: none; 
 
    background-color: #fff; 
 
    border: 1px solid #ccc; 
 
    border: 1px solid rgba(0,0,0,.15); 
 
    border-radius: 4px; 
 
    -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); 
 
    box-shadow: 0 6px 12px rgba(0,0,0,.175); 
 
} 
 
ul li{ 
 
    /*padding: 15px;*/ 
 
    background-color: #fff; 
 
    color: #4FB9A7; 
 
    margin-bottom: 1px; 
 
    cursor: pointer; 
 
} 
 
ul li a { 
 
    padding: 8px 20px; 
 
    color: inherit; 
 
    text-decoration: none; 
 
    display: block; 
 
} 
 
ul li a:hover{ 
 
    background-color: #4FB9A7; 
 
    color: #FFF; 
 
} 
 
input[type=checkbox]:checked ~ label { 
 
    background-color: #3D88BD; 
 
} 
 
input[type=checkbox]:checked ~ ul { 
 
    display: block; 
 
} 
 
ul .divider { 
 
    height: 1px; 
 
    margin: 9px 0; 
 
    overflow: hidden; 
 
    background-color: #e5e5e5; 
 
} 
 
.temperaturearea span#temp { 
 
    position: relative; 
 
    color: #000000; 
 
    font-size: 80px; 
 
} 
 
.temperaturearea #temp:after { 
 
    content: ''; 
 
    position: absolute; 
 
    height: 10px; 
 
    width: 10px; 
 
    top: 16px; 
 
    right: -17px; 
 
    border: 3px solid #000000; 
 
    border-radius: 50%; 
 
} 
 
.weather > span { 
 
    position: relative; 
 
    font-size: 1.2rem; 
 
} 
 
.weather > span:before { 
 
    content: ''; 
 
    position: absolute; 
 
    left: -10px; 
 
    top: 0px; 
 
    height: 3px; 
 
    width: 3px; 
 
    border: 2px solid #000; 
 
    border-radius: 50%; 
 
} 
 
.main-toggle span { 
 
    margin: 0 0 0 16px; 
 
} 
 
.main-toggle span:last-child { 
 
    margin-left: 11px; 
 
} 
 
.weather button { 
 
\t \t background: #6bbf6b; 
 
\t \t border: none; 
 
\t \t border-radius: 30px; 
 
\t \t outline: none; 
 
\t \t width: 45px; 
 
\t \t height: 20px; 
 
\t \t margin: 5px 5px 0; 
 
\t \t cursor: pointer; 
 
\t \t position: relative; 
 
\t \t transition: background .2s; 
 
} 
 
.weather button:active { 
 
\t \t background: #67b567; 
 
\t } 
 
.weather #unit-toggle { 
 
\t \t position: absolute; 
 
\t \t display: inline-block; 
 
\t \t left: -8px; 
 
\t \t top: 2px; 
 
\t \t width: 15px; 
 
\t \t height: 15px; 
 
\t \t background: #fff; 
 
\t \t border-radius: 50%; 
 
\t \t transition: left .2s; 
 
} 
 
#unit-toggle.toggle { 
 
\t \t left: 16px; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<div class="wrapper"> 
 
    <div class="container"> 
 
    <div class="header"><h1>Local Weather</h1></div> 
 
    <div class="weatherbox"> 
 
     <div class="cityarea"> 
 
     <h2 id="cityname"></h2> 
 
     </div> 
 
     <div class="countryarea"> 
 
     <h3 id="state"></h3> 
 
     <h3 id="country"></h3> 
 
     </div> 
 
     <div class="dropdownlocation"> 
 
     <div class="dropdown"> 
 
     <input type="checkbox" id="checkbox-toggle"> 
 
    <label for="checkbox-toggle"><i class="fa fa-globe" aria-hidden="true"></i><i class="fa fa-caret-down" aria-hidden="true"></i></label> 
 
    <ul id="testMenu"> 
 
     <li><a href="#">Current Location</a></li> 
 
     <li class="divider"></li> 
 
     <li class="dropdown-header">Main Cities</li> 
 
    </ul> 
 
     </div> 
 
     </div> 
 
    <div class="temperaturearea"> 
 
     <div> 
 
     <span id="wicon"></span> 
 
     </div> 
 
     <div id="wdescription"></div> 
 
     <span id="temp"></span> 
 
     <div class="weather main-toggle"> <!-- Begin Unit Switch --> 
 
     <span>F</span> 
 
     <button id="unit-switch"><span id="unit-toggle"></span></button> 
 
     <span>C</span> 
 
    </div> 
 
    </div> 
 
    </div> 
 
    </div> 
 
</div>

ответ

1

Есть несколько проблем, с кодом, так как вы определили все свои функции и переменную внутри document.ready вы можете» t доступ к любой из этих функций и переменной вне document.ready. Вот почему, когда вы вызываете 'testWeather' на onclick li, он выбрасывает 'testWeather' не определен. Чтобы решить эту проблему (вы должны сделать свои переменные и глобальные функции), вы должны определить все переменные за пределами document.ready. Просто держите только ниже двух строк кода внутри document.ready. $(".cityarea").html(getLocation); testMenu();

Но это будет просто решить «testWeather» не определен вопрос, и есть onre дополнительной эмиссии в вашем коде, внутри testWeather функции там, вы используете одно свойство под названием testLocation, который не определен, так что вы будете получите ошибку JavaScript здесь. Вы сохранили свои тестовые позиции в переменной mainCities, поэтому вы должны использовать mainCities вместо testLocation. Эти два изменения заставят ваше приложение работать без ошибок. Здесь скорректирован код JavaScript. Есть еще одна незначительная ошибка вашего кода, то, как вы читаете текущий город, неверно.

$(document).ready(function() { 
    $(".cityarea").html(getLocation); 
    testMenu(); 
}); 
    var currentLat; 
    var currentLong; 
    var currentCity; 
    var currentRegion; 
    var currentCountry; 

    var mainCities = { 
     'San_Francisco': { 
      'region': 'California', 
      'country': "United States", 
      'lat': 37.7749300, 
      'lon': -122.4194200 
     }, 
     'St._Louis': { 
      'region': 'Missouri', 
      'country': "United States", 
      'lat': 38.6272700, 
      'lon': -90.1978900 
     }, 
     'Miami': { 
      'region': 'Florida', 
      'country': "United States", 
      'lat': 25.7742700, 
      'lon': -80.1936600 
     }, 
     'Tokyo': { 
      'region': 'Tokyo', 
      'country': "Japan", 
      'lat': 35.689500, 
      'lon': 139.6917100 
     } 
    }; 

    function testMenu() { 
     for (var place in mainCities) { 
      var city = place.replace(/_/g, ' '); 
      $('#testMenu').append("<li onclick=testWeather('" + place + "');><a href='#'>" + city + "</a></li>"); 
     } 
    }; 

    function testWeather(cityLocation) { 
     currentLat = mainCities[cityLocation].lat; 
     currentLong = mainCities[cityLocation].lon; 
     currentRegion = mainCities[cityLocation].region; 
     currentCity = mainCities[cityLocation]; 
     currentCountry = mainCities[cityLocation].country; 

     getWeather(); 

    }; 

    function getLocation() { 
     $.getJSON('http://ip-api.com/json/?callback=?', function (data) { 

      currentRegion = data.regionName; 
      currentCity = data.city; 
      currentCountry = data.country; 
      currentLat = data.lat; 
      currentLong = data.lon; 

      //$("#cityname").text(currentCity); 

      getWeather(); 

     }); 
    }; 

    function getWeather() { 

     $("#cityname").text(currentCity); 
     $("#state").text(currentRegion); 
     $("#country").text(currentCountry); 

     $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + currentLat + '&lon=' + currentLong + '&units=imperial&APPID=e656b9ee098cf2341fcfdb365b96b4a8', function (json) { 

      var showfahrenheit = true; 
      var tempfahrenheit = Math.round(json.main.temp); 
      var temcelcius = Math.round((tempfahrenheit - 32) * 5/9); 

      $("#temp").html(tempfahrenheit); 

      $('#unit-switch').on('click', function() { 
       if (showfahrenheit === false) { 
        $("#temp").html(tempfahrenheit); 
        showfahrenheit = true; 
       } else { 
        $("#temp").html(temcelcius); 
        showfahrenheit = false; 
       } 

       $("#unit-toggle").toggleClass("toggle"); 
       //$('#temp').toggleClass('toggle'); 
      }); 

     }); 
    }; 
+0

Спасибо! Я уже выяснил некоторые проблемы и заменил 'testLocation' на' MainCities' к тому времени, когда вы разместили это решение. Я исправил остальное на основе вашего решения, и он работает. Однако есть проблема. Всякий раз, когда я нажимаю на местоположение, он показывает только [объект Object] вместо имени города. Я не мог понять, что не так. –

+0

Проблема с названием города заключается в том, что вы назначаете текущий город как «mainCities [cityLocation]», который является объектом, а не строкой. Чтобы получить правильное имя, используйте 'cityLocation.replace (/ _/g, '')'. Надеюсь это поможет. – Paks

+0

Большое спасибо !!! –