Search code examples
google-mapsgoogle-maps-api-3geocodegoogle-geocoder

Converting address to geocode, just returns "undefined", why?


This is what i have:

http://jsfiddle.net/JhCKW/1/

Im using Google maps v3, Geocode.

I made a function showAddress( param ). This takes the param, check if its a address if it is then it returns cords and if its not it returns 0.

If you check the link, you can see I have written the code for this, but I just get a alert "undefined".

What is wrong here?


Solution

  • Oh, I've finally realised the case. Problem is not in Google Maps. You are returning result not from showAddress but from callback. So, it's actually goes nowhere. You need to display your result using callback also. Just like this:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
    
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
    <script type="text/javascript">
      var geocoder;
      function showAddress(address, callback)
      {
        if (typeof(geocoder) == 'undefined') geocoder = new google.maps.Geocoder();
    
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            callback(results[0].geometry.location);
          } else {
            callback(0);
          }
        });
      }
    
      $(document).ready(function(){
        $('#address').blur(function(){
          showAddress( $('#address').val(), function(result)
          {
            if (result === 0)
              alert('Adressen not found');
            else{
              alert(result);
              $('#cords').val( result );
            }
          });
        });
      });
    </script>
    
    <input type="text" name="address" id="address">
    

    You can check it working here: http://jsfiddle.net/BgDQc/2/