Search code examples
jsonapigeolocation

Im using geolocation() api but JSON is not passing


I'm using geolocation() to get the user's location, then I want to use the longitude and latitude and insert at the end of the URL https://fcc-weather-api.glitch.me/api/current?lon= When I test my var myURL in the browser's console I get the full successful path https://fcc-weather-api.glitch.me/api/current?lon=-117.32051229999999&lat=33.1412124

Problem: My JSON is not passing.

/*
 * 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;
};

This is my HTML just in case if someone wants to see.

 <span id="city">#CITY</span><br>
 <div id="description">#DESCRIPTION</div>
 <span id="temp">#Temp°</span>

Solution

  • After thinking I realized one short path. Inside of the function showPosition(position) I added a jQuery .get calling my JSON file.

    Just update the function below

    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;
        });
    };