title: Return value with google maps geocoder
body: <p>I just can't find what's wrong with this bit of code:</p>
  
  <pre><code>function getLocationName(latitude, longitude) {
      if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) {
          return false;
      }
  
      var locationName;
      var geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(latitude, longitude)
  
      // Reverse Geocoding using google maps api.
      geocoder.geocode({ 'latLng': latlng }, function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              if (results[1]) {
                  locationName = results[1].formatted_address;
                  alert(locationName);
              }
              else {
                  locationName = "Unknown";
              }
          }
          else {
              locationName = "Couldn't find location. Error code: " + status;
          }
      });
      alert(locationName);
      return locationName;
  
  }
  </code></pre>
  
  <p>I call this from a jquery event handler like this:</p>
  
  <pre><code>$("#id").on("event", function (event, ui) {
      $("#userLocation").text(getLocationName(latitude, longitude));
  });
  </code></pre>
  
  <p><s>Weird part is that the first alert gets the correct value of 'locationName' but the second one always returns 'undefined'. I tried initializing the variable with a value and in that case the first alert again returned the correct location name but the second one returned the initialization value. This gives me a notion that this might be a variable scope related problem but I just can't figure what.</s></p>
  
  <p>PS. I don't have any other variables (local/global) by the same name.</p>
  
  <p><strong>Update</strong>: The alert works fine now (thanks to Lwyrn's answer) but the return value is still wrong. I've followed the answers in the linked SO question and still I couldn't 'return' the right value. The alert did work fine.</p>