I need a function in JavaScript that can access an API to get the latitude coordinate for a particular IP address. The current function can print the latitude in the console when called. When I return the value, it is returned as undefined. I cannot get the function to return the value I have accessed from the API.
I have tried declaring the variable in numerous locations and have altered the function numerous times, but I cannot get the function to return or print anything but 'undefined' when outside of the internal function.
// Code for function
function latitude(ip)
{
var latitudeData;
var access_key = '*******';
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'http://api.ipstack.com/' + ip + '?access_key=' + access_key, true);
request.onload = function test () {
// Begin accessing JSON data here
latitudeData=data.latitude;
console.log(latitudeData); // This will print required value. **
return latitudeData;
}
}
// Send request
request.send();
return test(); // get error from this line.
}
var ip = '134.201.250.155';
var p =latitude(ip);
console.log(p); // This will print undefined **