title: Creating a callback to return an array from a function
body: <p>I am trying to learn Node.js</p>
  
  <p>I am having trouble creating my own call back on a function. It seems like such a simple thing but I don't quite understand how to do it. </p>
  
  <p>The function is passed an address (example: "1234 will ln, co") which uses google's geolocate json api to return the full address, latitude and longitude in an array.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>//require secure http module
  var https = require("https");
  
  //My google API key
  var googleApiKey = "my_private_api_key";
  
  //error function
  function printError(error) {
      console.error(error.message);
  }
  
  function locate(address) {
  //accept an address as an argument to geolocate
  
      //replace spaces in the address string with + charectors to make string browser compatiable
      address = address.split(' ').join('+');
  
      //var geolocate is the url to get our json object from google's geolocate api
      var geolocate = "https://maps.googleapis.com/maps/api/geocode/json?key=";
      geolocate += googleApiKey + "&amp;address=" + address;
  
      var reqeust = https.get(geolocate, function (response){
  
          //create empty variable to store response stream
          var responsestream = "";
  
          response.on('data', function (chunk){
              responsestream += chunk;
          }); //end response on data
  
          response.on('end', function (){
              if (response.statusCode === 200){
                  try {
                      var location = JSON.parse(responsestream);
                      var fullLocation = {
                          "address" : location.results[0].formatted_address,
                          "cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng
                      };
                      return fullLocation;
                  } catch(error) {
                      printError(error);
                  }
              } else {
                  printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"});
              }
          }); //end response on end
  
      }); //end https get request
  
  } //end locate function
  </code></pre>
  
  <p>So when I try to execute my function</p>
  
  <pre><code>var testing = locate("7678 old spec rd");
  console.dir(testing);
  </code></pre>
  
  <p>The console logs undefined because its not waiting for the return from locate (or at least I am guessing this is the problem).</p>
  
  <p>How do i create a call back so when the locate function returns my array, it runs the console.dir on the array it returned.</p>
  
  <p>Thanks! I hope my question makes sense, im self taught so my tech jargon is horrible. </p>