Why does JSON remain unchanged when a value is explicitly assigned in Javascript

Why isn't my JSON structure updating when I explicitly assign a new value?

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

I am trying to reverse geocode the latitude and longitude to obtain the human address, which is working fine. However, I cannot insert it into the JSON. Why is that?

Here is the example in action:

Click here for the live demo

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");

Answer №1

Make sure to wrap all your code within the callback function for proper execution:

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 additional code should be placed before the above function
}

As mentioned in the comments, this is related to AJAX and handles asynchronous tasks. The geocoder.geocode function initiates an AJAX call.

Answer №2

There are a couple of issues with the code that need to be addressed :

1) There seems to be different scopes for the "address" variable declared as var address = ""; and var address = results[1].formatted_address; in the code.

2) The asynchronous response needs to have an action to append to ("#items") within the callback function.

Code has been updated accordingly and tested on JSFiddle for verification:

//GEOCODER
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);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the selected input from numerous checkboxes in a React code and saving them within a blank array

I am currently working on a React project where I have multiple checkboxes that interact with a single component. The data in this component is supposed to change based on the checkbox that is selected. However, I am struggling to keep track of which check ...

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

Conflict in Vue.js between using the v-html directive and a function

Below is the component template for a notification: <template> <div> <li class="g-line-height-1_2"> <router-link :to="linkFromNotification(item)" @click.native="readNotification(item)" v-html="item. ...

Error: Headers cannot be set after they have already been sent, resulting in an Unhandled Promise Rejection with rejection id 2

I'm a beginner with Node.js and I've been using express.js. In a section of my code, I'm trying to retrieve data from a form via AJAX and store it in a variable called url. I have access to request.body, but I'm encountering an issue wh ...

Learn how to use shell jq to dynamically parse a JSON object

I have a question regarding the use of shell's jq. Here is my JSON object: {"1543446000": {"name": "John", "company": "foo"}, "1543359600": {"name": "Kate", "company": "bar"}} The numbers 1543446000 and 1543359600 represent UNIX timestamps. How can ...

Model for handling Node/Express requests

I always saw Node.js/Express.js route handlers as akin to client-side EventListeners such as onClick, onHover, and so on. For example: document .getElementById('btn') .addEventListener('click', function() { setTimeout(functi ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

django, the X-CSRFToken in the request header is improperly configured

Essentially, I have managed to successfully send a CSRF token to the frontend and store it in the cookie section of the application tab within the developer console of the browser with this code: @method_decorator(ensure_csrf_cookie) def get(self, ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...

Steps for preventing form submission when the username is unavailable

After checking the availability of the user name, I encountered an issue where the form still gets submitted even if the username is not available. Updated Code: <SCRIPT type="text/javascript"> $(document).ready(function(){ $("#emailch").change(fu ...

Lag in responsiveness of iOS devices when using html5 applications

My HTML5 video app includes a combination of video, a JavaScript swipable playlist, and other animated overlays. When using the app on iOS, the performance of playlist swiping and overlay animations is great upon initial load. However, after playing a vid ...

attempting to link to an external style sheet hosted on Amazon S3

I am working on creating a widget or snippet of a website that can easily be added to another webpage by including a script tag for my JavaScript file hosted on Amazon S3 and a div element where content will be inserted. Even though I have uploaded the C ...

An error occurred in the defer callback: The specified template "wiki" does not exist

I recently developed a Meteor package called Wiki. Within the package, I included a wiki.html file that contains: <template name="wiki"> FULL WIKI UI CODE HERE </template> Next, I created a wiki.js file where I defined my collections and eve ...

How can I employ CSS files within a Node module that is compatible with Next?

I recently made the switch from Gatsby to Next and I'm still learning the ropes. When working with Gatsby, I had a Node module that served as my UI library across different projects. This module utilized a CSS module file (style.module.css) that coul ...

Tips for extracting a nested key value from a JSON data structure

I am working with a PostgreSQL table CREATE TABLE IF NOT EXISTS account_details ( account_id integer, condition json ); The table contains the following data account_id condition 1 [{"action":"read","subject": ...

Determine the exposed area of an element with overflowing content

I am looking for a way to determine which text within an element (such as a div or textbox) is currently visible when there is overflow. As the user scrolls, I need to have an updated list of the visible text. I am open to using any elements, but only a ...

Utilizing API data to set the state in a React component

In my quest to modify the state of this React component, I have a variable called rankAndTeam that holds the "prints=>" data listed below. My goal is to assign "Washington Capitals" to this.state.teamRank["0"], "New York Islanders" to this.state.teamRan ...

I am facing issues with running my project due to a gyp error. Can anyone provide guidance on resolving this problem?

Every time I execute my code, I encounter the same persistent error. Despite attempting to resolve it by uninstalling and reinstalling Node and npm, the issue persists. Furthermore, the lack of "node_modules" exacerbates the problem. How can I rectify this ...

Display every single value found within the dictionary object retrieved using .json() method

I am using a code snippet that enables me to display dictionary items returned by the .json() method on an XHR response from a website: teamStatDicts = responser[u'teamTableStats'] for statDict in teamStatDicts: print("{seasonId},{tournament ...

Using a number input with step increments of 0.01 in AngularJS can result in undefined values for specific inputs

An issue arises when using a specific type of input in angularjs (1.6.1) where the values between 9.03 to 9.05 inclusively return undefined. This problem also occurs with other values like 9.62, 9.63, and 17.31. <input type="number" step="0.01" data-ng ...