I'm trying to store the values of the latitude and the longitude from the response that I get from the Google Geocoding API. Right now I am using a fixed location in California. My HTTP request keeps returning undefined.
I've been looking around a lot and I see that people have this same problem, but I can't wrap my head around making a callback function which seems to be the solution, could anybody explain to me how to do this? I know that my CORS request is working because I am using it to talk GET from a Heroku server that I set up.
var geocode = new XMLHttpRequest();
geocode = createCORSRequest('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=');
geocode.onload = function() {
var geoData = JSON.parse(geocode.responseText); // parse the JSON from geocode response
var results = geoData["results"]; // create variable for results
var userLong = results["geometry"]["location"]["lng"]; // parse the latitude
var userLat = results["geometry"]["location"]["lat"]; // parse the longitude
console.log(userLong);
console.log(userLat);
}
createCORSRequest()
// Create the XHR object.
function createCORSRequest(method, url) {
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, false);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}