Returning json array from a function to a variable-Collection of common programming errors

  • Try like this:

    function map_address(addr, callback) {
    
        var input_address = addr;
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode( { address: input_address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat();
                var lng = results[0].geometry.location.lng();
    
    
                                   jsonarr={'lat':lat,'lng':lng}
                                   alert(jsonarr.lat);
                                   callback(jsonarr) ;
    
    
                                }
            else {
                alert("Nessuna coordinata trovata da questo indirizzo!");
                }
            });
    }
    map_address("hogehoge", function(result){
      alert(result)
    });
    
  • the geocoder.geocode(..); function is asynchronous as it wraps another function inside that will be called later when the geocode operation is done.

    because of this map_address(...) will always return undefined

  • Thanks all for the answers, i put all my code inside the callback and all work fine this is the final code.

       function map_address(addr,callback)
            {
    
                var input_address = addr;
                var geocoder = new google.maps.Geocoder();
                geocoder.geocode( { address: input_address }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) 
                    {
                        var lat = results[0].geometry.location.lat();
                        var lng = results[0].geometry.location.lng();
    
                        jsonarr={'lat':lat,'lng':lng}                       
                        return callback(jsonarr);                        
                    }
                    else {
                        alert("No coord find");
                    }
                });
            }
    
    
    $(document).ready(function(){ 
       $(window).load(function(){ 
    
    map_address('address string',function(coord){
    
    
      var center=new google.maps.LatLng(coord.lat,coord.lng);
    
    
    
      var settings = {
              zoom: 16,
              center: center,
              mapTypeControl: false,
              mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
              navigationControl: true,
              navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
              mapTypeId: google.maps.MapTypeId.ROADMAP
          }; 
    
      var map=new google.maps.Map(document.getElementById("map"), settings);
    
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(coord.lat,coord.lng),
    map: map
    });
    
    
    });
    });
    
    });
    

Originally posted 2013-11-09 23:09:52.