我正在使用geolocation()
来获取用户的位置,然后我想使用经度和纬度并在网址末尾插入https://fcc-weather-api.glitch.me/api/current?lon=
当我测试var myURL
时浏览器的控制台我得到了完整的成功路径https://fcc-weather-api.glitch.me/api/current?lon=-117.32051229999999&lat=33.1412124
问题:我的JSON没有通过。
/*
* HTML5 geolocation()
*/
var demo = document.getElementById('demo');
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
demo.innerHTML = "Sorry, Geolocation is not supported by this browser.";
}
};
getLocation();
function showPosition(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
myURL = "https://fcc-weather-api.glitch.me/api/current?lon=" + lon + "&lat=" + lat;
};
var lat;
var lon;
var myURL;
var request = new XMLHttpRequest();
request.open('GET', myURL);
request.responseType = 'json';
request.send();
/*
* TO GET JSON CONTENT
*/
request.onload = function () {
var superHeroes = request.response;
populateHeader(superHeroes);
getFah(superHeroes);
getCelsius(superHeroes);
};
function populateHeader(jsonObj) {
document.getElementById('city').innerHTML = jsonObj.name;
document.getElementById('description').innerHTML = jsonObj.weather[0].description;
document.getElementById('temp').innerHTML = jsonObj.temp;
};
这是我的HTML,以防万一有人想看。
<span id="city">#CITY</span><br>
<div id="description">#DESCRIPTION</div>
<span id="temp">#Temp°</span>
答案 0 :(得分:0)
在想到我实现了一条短路之后。在function showPosition(position)
内部,我添加了一个jQuery .get
来调用我的JSON文件。
只需更新下面的function
function showPosition(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
myURL = "https://fcc-weather-api.glitch.me/api/current?lon=" + lon + "&lat=" + lat;
$.get(myURL, function (data) {
document.getElementById('city').innerHTML = data.name;
document.getElementById('country').innerHTML = data.sys.country;
document.getElementById('description').innerHTML = data.weather[0].description;
});
};