在应用中更改经度和纬度时遇到问题 Javascript

Having trouble changing longitude and latitude in app Javascript

我正在使用 vanilla javascript 创建一个天气应用程序,该应用程序的一个功能是单击一个按钮并让它随机化一个新的经度和纬度,以便它可以更改位置,从而更改温度.我陷入了困境,无论何时单击按钮都没有任何反应,但每当我 console.log 它时,它就会出现在控制台中:

changeLocationBtn.addEventListener("click", function(){
                longitude = (Math.random() * (80 + 180) + -180).toFixed(3);
                latitude = (Math.random() * (90 + 90) + -90).toFixed(3);
                console.log(latitude, longitude);
            });

我真的不知道发生了什么。

// Selectors
const degreeCelcius = document.querySelector(".celcius");
const weatherDescription = document.querySelector(".description");
const changeLocationBtn = document.querySelector(".change-location-btn");
const weatherLocation = document.querySelector(".location");

// Event Listeners
window.addEventListener("load", () => {
  let longitude;
  let latitude;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
      longitude = position.coords.longitude;
      latitude = position.coords.latitude;

      // Here lies the problem
      changeLocationBtn.addEventListener("click", function() {
        longitude = (Math.random() * (80 + 180) + -180).toFixed(3);
        latitude = (Math.random() * (90 + 90) + -90).toFixed(3);
        console.log(latitude, longitude);
      });

      const corsProxy = 'https://cors-anywhere.herokuapp.com/';
      const api = `${corsProxy}http://api.weatherapi.com/v1/current.json?key=7391e8544809410cbf0120949201511&q=${latitude}, ${longitude}`;

      // Fetch data from the API
      fetch(api)
        .then(response => {
          return response.json();
        })
        .then(data => {
          console.log(data);
          const {
            temp_c,
            condition
          } = data.current;

          degreeCelcius.textContent = temp_c + '°C';
          weatherDescription.textContent = condition.text;
          weatherLocation.textContent = data.location.name + ", " + data.location.country;
        });
    });
  }
});
.btn-div {
  height: 250px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: end;
  -ms-flex-align: end;
  align-items: flex-end;
}

.btn-div .change-location-btn {
  background-color: #f82626;
  color: white;
  outline: none;
  border: none;
  border-radius: 0px 0px 10px 10px;
  width: 100%;
  height: 50px;
  text-transform: uppercase;
  font-weight: 500;
  letter-spacing: 3px;
  font-size: 15px;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

.btn-div .change-location-btn:hover {
  background-color: #f56969;
  cursor: pointer;
}

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  background: linear-gradient(190deg, #77dfbc, #8b54e6);
  overflow: hidden;
}

.container {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 100vh;
}

.weather-container {
  background-color: #f5e3e3;
  border-radius: 10px;
  height: 400px;
  width: 300px;
  -webkit-box-shadow: 0px 0px 10px 0px #131212b2;
  box-shadow: 0px 0px 10px 0px #131212b2;
  padding-top: 50px;
  text-align: center;
  font-family: 'Montserrat', sans-serif;
}

.weather-container h1 {
  font-size: 50px;
  margin-bottom: 2px;
}

.weather-container h4 {
  font-weight: 600;
}


/*# sourceMappingURL=style.css.map */
<div class="container">
  <div class="weather-container">
    <h1 class="celcius">Celcius</h1>
    <h4 class="description">Sunny Day</h4>
    <h4 class="location">Planet Vegeta</h4>

    <div class="btn-div">
      <button class="change-location-btn">Change Location</button>
    </div>
  </div>
</div>

您可以检查 changeLocationBtn 是否确实存在并且在侦听器绑定时被发现也最好在 changeLocationBtn.addEventListener 附近添加 changeLocationBtn 选择器以检查它是否仍在上下文中。

 const changeLocationBtn = document.querySelector(".change-location-btn");
 console.log('btn', changeLocationBtn )
 changeLocationBtn.addEventListener("click", function() {
        longitude = (Math.random() * (80 + 180) + -180).toFixed(3);
        latitude = (Math.random() * (90 + 90) + -90).toFixed(3);
        console.log(latitude, longitude);
  });

从这里开始:

 // Event Listeners
window.addEventListener("load", () => {
  let longitude;
  let latitude;

  const degreeCelcius = document.querySelector(".celcius");
  const weatherDescription = document.querySelector(".description");
  const changeLocationBtn = document.querySelector(".change-location-btn");
  const weatherLocation = document.querySelector(".location");

  // Here lies the problem
  changeLocationBtn.addEventListener("click", function() {
    longitude = (Math.random() * (80 + 180) + -180).toFixed(3);
    latitude = (Math.random() * (90 + 90) + -90).toFixed(3);
    console.log(latitude, longitude);
  });

您当前的代码仅在页面加载时发送一个数据。我修改了 JS 代码以同时使用 onLoad 和 click 事件模式。但是改变显示的数据非常缓慢。 我体验过天气API只适用于地面坐标,不适用于海洋

const degreeCelcius = document.querySelector(".celcius");
const weatherDescription = document.querySelector(".description");
const changeLocationBtn = document.querySelector(".change-location-btn");
    
const weatherLocation = document.querySelector(".location");

const corsProxy = 'https://cors-anywhere.herokuapp.com/';

function change_location(longitude,latitude){
                
    const api = ${corsProxy}http://api.weatherapi.com/v1/current.json?key=7391e8544809410cbf0120949201511&q=${latitude}, ${longitude}`;

    // Fetch data from the API
    fetch(api)
    .then(response => {
        //console.log(response);
        return response.json();
    })
    .then(data => {
        console.log(data);
        const {
           temp_c,
           condition
        } = data.current;

        degreeCelcius.textContent = temp_c + '°C';
        weatherDescription.textContent = condition.text;
        weatherLocation.textContent = data.location.name + ", " + data.location.country;
    });
}

// Event Listeners
window.addEventListener("load", () => {
    let longitude;
    let latitude;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            longitude = position.coords.longitude;
            latitude = position.coords.latitude;
            console.log("Current location: " + latitude, longitude);

            change_location(longitude,latitude);
        });
    }
});

changeLocationBtn.addEventListener("click", function() {
    longitude = (Math.random() * (80 + 180) + -180).toFixed(3);
    latitude = (Math.random() * (90 + 90) + -90).toFixed(3);
    console.log(latitude, longitude);

    change_location(longitude,latitude);
});`