-1

Why my JSON structure does not update when I explicit assign a new value?

items[0][i]['human_addressItem'] = address;

I am geo reversion latitude and Longitude to take the Human address, that part is working fine, but I can insert it into the JSON, why?

This is the example running:

http://jsfiddle.net/KGbRh/

CODE:

HTML:

<script src="http://code.jquery.com/jquery-2.0.2.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div class="container-fluid">
    <!-- Tables -->
    <section id="tables">
        <table>
            <thead>
                <tr>
                    <th>[name]</th>
                    <th>[txtLat]</th>
                    <th>[txtLon]</th>
                    <th>[human_address]</th>
                </tr>
            </thead>
            <tbody id="items">
                <script id="tmpItems" type="text/html">
                    <tr>
                    <td><input value="${name}" type="text" name="[name]"></td>
                    <td><input value="${Latitude}" type="text" name="[txtLat]"></td>
                    <td><input value="${Longitude}" type="text" name="[txtLon]"></td>
                    <td><input value="${human_addressItem}" type="text" name="[human_address]"></td>
                    </tr>
                </script>
            </tbody>
        </table>
    </section>
</div>

JAVASCRIPT:

 //GEOCORDER
    geocoder = new google.maps.Geocoder();
    items = [
        [{
            "Longitude": -73.929489,
                "Latitude": 40.76079,
                "name": "Electronics"
        }, {
            "Longitude": -73.761727,
                "Latitude": 40.695817,
                "name": "02 Dodge (PICS)"
        }], {
            "active": 0
        }];

    for (var i = 0; i < items[0].length; i++) {
        var address = "";

        var lat = parseFloat(items[0][i]['Latitude']);
        var lng = parseFloat(items[0][i]['Longitude']);
        var latlng = new google.maps.LatLng(lat, lng);
        geocoder.geocode({
            'latLng': latlng
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    var address = results[1].formatted_address;
                    //alert(address);
                    console.log(address);
                } else {
                    alert('No results found in: ' + items[0][i]['name']);
                }
            } else {
                alert('Geocoder failed due to: ' + status + " in: " + items[0][i]['name']);
            }
        });
        items[0][i]['human_addressItem'] = address;
    }
    var o = items;
    $("#tmpItems").tmpl(items[0]).appendTo("#items");
lito
  • 3,105
  • 11
  • 43
  • 71
  • 2
    Welcome to the wonderful world of **async**! You can't do that. – SLaks Jun 07 '13 at 17:16
  • 1
    Why not? how can I work around @SLaks ? – lito Jun 07 '13 at 17:19
  • Because the callback didn't run yet. You need to put everything in the callback. Consider using promises. – SLaks Jun 07 '13 at 17:20
  • 1
    Please include the code in your question, not in some external site that we have to open. – user229044 Jun 07 '13 at 17:20
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – JJJ Jun 07 '13 at 17:23
  • @Juhana this question is not related to AJAX, and uf you think u have the answer why don't resolve my problem??? http://jsfiddle.net/KGbRh/ instead of give a meaningless answer. – lito Jun 07 '13 at 17:27
  • 1
    How do you think the script is fetching data from Google? (Hint: it's AJAX.) The answer to the duplicate tells the root cause of the problem. In any case, here's a demo of a working script: http://jsfiddle.net/KGbRh/4/ – JJJ Jun 07 '13 at 17:40

2 Answers2

1

You need to put all of your post-response code in the callback function:

geocoder.geocode({'latLng': latlng}, 
  function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
            var address = results[1].formatted_address;
            alert (address);
            items[0][i]['human_addressItem'] = address;
            var o = items;
            //items[i]['human_addressItem']) now holds the address
            alert (items[i]['human_addressItem']);
        } else {
            alert('No results found in: ' + items[0][i]['name']);
        }
    } else {
        alert('Geocoder failed due to: ' + status + " in: " + items[0][i]['name']);
    }
  });
  //any code here will run before your function above
}

Per the comments above, this IS about AJAX and therefore Async. The geocoder.geocode function makes an AJAX call.

Josh Noe
  • 2,664
  • 2
  • 35
  • 37
1

A couple of errors in the code :

1) var address = ""; & var address = results[1].formatted_address; Different scope of address variables.

2) Asyc response. try appending to ("#items") in the callback

Updated code. Checked in JSFiddle

//GEOCORDER
geocoder = new google.maps.Geocoder();
items = [
    [{
        "Longitude": -73.929489,
            "Latitude": 40.76079,
            "name": "Electronics"
    }, {
        "Longitude": -73.761727,
            "Latitude": 40.695817,
            "name": "02 Dodge (PICS)"
    }], {
        "active": 0
    }];

    function updateAddress(i) {
       geocoder.geocode({
          'latLng': latlng
         }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                var address = results[1].formatted_address;
                //alert(address);
                console.log(address);
                items[0][i]['human_addressItem'] = address;

                var o = items;
                 $("#tmpItems").tmpl(items[0][i]).appendTo("#items");

            } else {
                alert('No results found in: ' + items[0][i]['name']);
            }
        } else {
            alert('Geocoder failed due to: ' + status + " in: " + items[0][i]['name']);
        }
    });   

  }

for (var i = 0; i < items[0].length; i++) {
    var address = "";

    var lat = parseFloat(items[0][i]['Latitude']);
    var lng = parseFloat(items[0][i]['Longitude']);
    var latlng = new google.maps.LatLng(lat, lng);

    updateAddress(i);
}
Kechit Goyal
  • 3,952
  • 3
  • 20
  • 21