Extract json array data using javascript

2.2k Views Asked by At

I would like to obtain the formatted_address from the json data returned from the following query string by using javascript.

http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true

function getReverseGeocodingData(lat, lng) {
    //use ajax and json
    $.ajax({
        type: "POST",
        url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+sessionStorage.latitude+","+sessionStorage.longitude+"&sensor=true",
        data: jsondata,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var address = response.Result;
            var error = response.Error;

            if (address != null) {
                alert("Found current location: " + address.formatted_address);
                sessionStorage.currentAddress = address.formatted_address;
                return;
            }
        },
        error: function (msg) {
            errorConnection();
        }
    });
}

I tried getting formatted_address but it return undefined.

4

There are 4 best solutions below

1
On

There are a few things to fix:

apparently you don't have to post data as you're making a GET request.

I rewrote your code to take the parameters from lat and lng in order to test it easily.

response is an object that contains an array of results objects (lowercase r plural). Each object contains a formatted_address property.

Most likely you'll want to fetch the first one:

response.results[0].formatted_address

function getReverseGeocodingData(lat, lng) {
    //use ajax and json
    $.ajax(
    {
        type: "GET",
        url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true",
        dataType: "json",
        success: function (response) {
            alert("Found current location: " + response.results[0].formatted_address);
        },
        error: function (msg) {
            alert('error');
        }
    });
}

To try it:

getReverseGeocodingData(44.4647452,7.3553838);

Outputs:

Found current location: Via Pasubio, 34, 12025 Dronero CN, Italia

1
On

just changed the success function with this, you will get all the formatted address

success: function (response) {
    var address = response.results;
    var error = response.error; //write exact word of the "error" which you get in response

    if(address.length > 0) {
        for(i=0; i<address.length; i++) {
            console.log("Found current location: " + address[i].formatted_address);
        }
    }
},
1
On

You can get formatted address like this (Ajax Success)

   success: function (results) {
        var address = (results[0].formatted_address);
              alert(JSON.stringify(address));
    },
2
On

Sorry my previous response only fixed the AJAX request- specifying contentType on a request is not required and has no impact - this is controlled by the server.

jQuery already will parse the request to an object, calling JSON.stringify on the response was causing the object to be parsed into a JSON formatted string, removing that line resolved the issue. Also specifying dataType didn't seem to be necessary.

It's worth noting that you're passing lat, and lng arguments to the function but not using them - I'd suggest either adding a lines like:

lat = lat || sessionStorage.latitude; 
lng = lng || sessionStorage.longitude; 

Below should be a solution complete with my suggestions:

function getReverseGeocodingData(lat, lng) {
    lat = lat || sessionStorage.latitude;
    lng = lng || sessionStorage.longitude;

    jsondata = {};
    //use ajax and json
    $.ajax({
        type: "POST",
        url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + sessionStorage.latitude + "," + sessionStorage.longitude + "&sensor=true",
        data: jsondata,

        success: function (response) {

            var address = response.results[0].formatted_address;
            var error = response.Error;
            if (address != null) {
                alert("Found current location: " + address);
                sessionStorage.currentAddress = address;
            }
        },
        error: function (msg) {
            errorConnection();
        }
    });
}