【问题标题】:Im using geolocation() api but JSON is not passing我正在使用 geolocation() api,但 JSON 没有通过
【发布时间】:2018-03-14 16:23:29
【问题描述】:

我正在使用geolocation() 来获取用户的位置,然后我想使用经度和纬度并在 URL 的末尾插入 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>

【问题讨论】:

  • 据我所知,你从来没有打电话给showPosition()

标签: json api geolocation


【解决方案1】:

经过思考,我意识到了一条捷径。在 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;
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2012-10-15
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多