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

Understanding how to parse a JSON array with various key-value pairs is crucial for

I have a project where I need to parse a JSON array with varying key names, such as: { "details": [ { "state": "myState1", "place": [ { "name": "placeName" } ] }, { "state": "myState2", "place": [ { "name1": "placeName ...

Switch up the linear gradient background periodically

Is there a way to change the background after a certain amount of time? It seems to work fine if the background color is just a solid color, but when it's a gradient as shown in the code below, the solution doesn't seem to work. Any suggestions f ...

Which method is considered more RESTful: creating a resource with a JSON payload or using regular POST parameters?

As I develop an API, I ponder whether to implement a factory endpoint that accepts a JSON payload with the resource attributes to be created, utilize regular application/x-www-form-urlencoded parameters in the request body, or if it's inconsequential ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...

What is the process for configuring environmental variables within my client-side code?

Is there a reliable method to set a different key based on whether we are in development or production environments when working with client-side programs that lack an inherent runtime environment? Appreciate any suggestions! ...

What is the solution for the error message "this.filters is not a function" in Vue.js 2?

Here is the code for my component: <script> import _ from 'lodash' export default{ props:['search','category'], data(){ return{ price_min:'', ...

Developing a feature that allows users to switch between different sets of information

I'm currently exploring a new project and attempting to design a toggle that switches between monthly and annual payments based on the user's selection, much like the functionality found here: . At present, I have implemented two sets of price c ...

How to convert the Unicode characters in Python for the string 'u05d9u05d7u05e4u05d9u05dd'?

Received a Json object from a URL with values formatted like this: title:'\u05d9\u05d7\u05e4\u05d9\u05dd' Attempting to convert these values into readable text, but struggling with them being interpreted as literal strin ...

NodeJS has a knack for replying even before the function has completed

Struggling with a NodeJS and Express API for a school project. The getAuthUserId function is not working as expected. It decodes the JWT token to retrieve the user Id from the mongoDB server. However, when calling this function in a REST call "/user/authT ...

The HTML table inexplicably displays a random comma out of nowhere

When working on my HTML table, I noticed that it was rendering a comma unexpectedly. I am using Nodemailer and SMTP Google server, and I suspect the issue lies within the HTML code. However, I am struggling to identify the exact problem. https://i.stack.i ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Exploring each item within oData: A guide

After writing the code statement above, I am able to see the attached image. Now, my challenge is accessing the "label" property inside each object. How can I iterate through these objects and retrieve their "label" properties? item.getModel().oData; I a ...

For each item they possess, attach a "!" at the end

Given an array, I am trying to use map to add an exclamation mark to each item in the array. For example: Before - items: ["ball", "book", "pen"] After - items: ["ball!","book!","pen!"] const array = [ { username: "john", team: "red", score: 5 ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

Refreshing browser data with JQuery ajax when the browser is refreshed

Is there a way in JavaScript or jQuery to stop the page from refreshing (F5) and only update certain parts of the page using Ajax? I attempted the following code, but it did not work: $(window).bind('beforeunload', function(event) { ...

Having difficulty rearranging choices within an optgroup

This is a dropdown <select id="officer-id" placeholder="Choose an officer"> <option selected="selected" >----</option> <optgroup id="pt1" label="To be reviewed"> <option value=&ap ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

The process of eliminating body padding in Nuxt.js

I'm considering building a website using Nuxt.js because I've heard it's both cool and user-friendly. While I do have some knowledge of vue.js, I'm stuck on a particular issue: How can I remove the padding from the body? I understand ...

Is there a way to retrieve the Angular-Redux store in a child module?

Within my Angular application, I utilize angular-redux for managing the application state. In my main module, I have defined the redux store in the following manner: export class MainModule { constructor(private ngRedux: NgRedux<MainAppState>, ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...