我正在codepen建立本地天气应用程序。我使用geolocation.getCurrentPosition()
方法获取当前位置,将相应的经度和纬度值存储在lat
和lng
变量中。虽然当我使用console.log()语句时,似乎根本不返回经度和纬度值。我在控制台中收到以下消息:
在不安全的起源上不推荐使用getCurrentPosition()和watchPosition()。要使用此功能,您应该考虑将应用程序切换到安全的来源,例如HTTPS。有关详细信息,请参阅https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins。
由于顶部条的密度很高,因此停止执行:对象
虽然我有点得到第一个错误,但我完全失去了接下来的两个并且谷歌搜索没有回复任何注释。 以下是我的Javascript代码:
$(document).ready(function() {
var location = document.getElementsByClassName("location");
getLocation();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
}
}
function getPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log(lat);
var weatherURL = "http://api.wunderground.com/api/c1d9333a91ec52f6/conditions/q/" + lat + "," + lng + ".json",
forecastURL = "https://api.wunderground.com/api/c1d9333a91ec52f6/forecast/q/" + lat + "," + lng + ".json";
$.getJSON(weatherURL, weatherJSON);
function weatherJSON(jsonVal) {
console.log(jsonVal);
var currentLocation = jsonVal.currentObservation.display_location.full;
location.innerHTML = currentLocation;
}
}
});
我希望读者能够解释错误并提供解决方案,以便最终的日志语句向控制台显示getJSON方法提取的完整JSON文件。
答案 0 :(得分:2)
好的,我已经成功调试了你的代码。
1)getCurrentPosition() and watchPosition() are deprecated on insecure origins
这是因为如果请求的网站使用的是HTTP而非HTTPS,则Chrome禁止获取位置。解决方案:通过https://
2)由于上述问题,您还必须使用HTTPS加载wunderground。的 https://api.wunderground.com/api/(...) 强>
X)Stopping the execution because density of top bars is high: Object
我在控制台中没有看到错误。
X)pen.js:95 Uncaught ReferenceError: navi is not defined
与上述相同。
4)你有一个拼写错误,其中lon
应 lng
5)您有另一个错字,您正在使用此属性.currentObservation
访问JSON,该属性不存在,应该是 .current_observation
6)不要将location
用于变量名,它引用浏览器的内部window.location
对象。解决方案:将其更改为 locationDiv
6.1)在代码的第二行,你有var locationDiv = document.getElementsByClassName("location")
,你可以检索一个数组。如果要实际分配元素,则必须添加索引: document.getElementsByClassName(“location”)[0]
将其应用于代码顶部的其他元素。
综上所述,这里有一个可用的codepen:https://codepen.io/anon/pen/jAvgRX
注意:现在我看到您使用更短的codepen进行了更新。我正在你的第一个代码中工作。