这是我的应用程序的JavaScript代码
var APPID = "fa89e6e41d40d7766082a8eb31cb25bb";
var temp;
var loc;
var icon;
var humidity;
var wind;
var direction;
function update(weather) {
icon.src = "imgs/codes/" + weather.code + ".png"
humidity.innerHTML = weather.humidity;
wind.innerHtml = weather.wind;
direction.innerHTML = weather.direction;
loc.innerHTML = weather.location;
temp.innerHTML = weather.temp;
}
window.onload = function () {
temp = document.getElementById("temperature");
loc = document.getElementById("location");
icon = document.getElementById("icon");
humidity = document.getElementById("humidity");
wind = document.getElementById("wind");
direction = document.getElementById("direction");
/* NEW */
if(navigator.geolocation){
var showPosition = function(position){
updateByGeo(position.coords.latitude, position.coords.longitude);
}
navigator.geolocation.getCurrentPosition(showPosition);
} else {
var zip = window.prompt("Could not discover your location. What is your zip code?");
updateByZip(zip);
}
}
/* NEW */
function updateByGeo(lat, lon){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + lat +
"&lon=" + lon +
"&APPID=" + APPID;
sendRequest(url);
}
function updateByZip(zip){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"zip=" + zip +
"&APPID=" + APPID;
sendRequest(url);
}
function sendRequest(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
weather.code = data.weather[0].id;
weather.humidity = data.main.humidity;
weather.wind = data.wind.speed;
/* NEW */
weather.direction = degreesToDirection(data.wind.deg)
weather.location = data.name;
/* NEW */
weather.temp = K2F(data.main.temp);
update(weather);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function degreesToDirection(degrees){
var range = 360/16;
var low = 360 - range/2;
var high = (low + range) % 360;
var angles = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
for( i in angles ) {
if(degrees >= low && degrees < high){
console.log(angles[i]);
return angles[i];
console.log("derp");
}
low = (low + range) % 360;
high = (high + range) % 360;
}
return "N";
}
function K2F(k){
return Math.round(k*(9/5)-459.67);
}
function K2C(k){
return Math.round(k - 273.15);
}
Html代码
<html>
<head>
<title>Weather App</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
Temprature: <span id="temperature">0</span>° <br>
Location: <span id="location">Unknown</span><br>
humidity: <span id="humidity">0</span>% <br>
Wind: <span id="wind">0</span> mph <span id="direction">N</span>
</body>
</html>
答案 0 :(得分:0)
虽然您的问题没有说明您使用的是HTTP还是HTTPS,但我相信我已经知道了这个问题。您的网络服务器需要配置启用HTTPS才能使某些地理定位功能正常工作。
我建议您查看浏览器控制台是否存在错误,正如@samgak建议的那样。您可能会收到一条错误消息,指出getCurrentPosition()
在不安全的来源上已被弃用。如果是这种情况,请参阅Deprecating Powerful Features on Insecure Origins以获取更多信息。