Lulzim
Lulzim

Reputation: 905

getJSON returns undefined

I want to get the latitude and longitude from the returning JSON format but it returns me undefined

this is my code so far , the json format please have a look at the URL what exactly returns

$.ajax({
    type: 'GET',
    url: "http://maps.googleapis.com/maps/api/geocode/json?address=Garibaldi,Prishtina&sensor=true",
    dataType: 'json',
    success: function (data) {

        $.each(data, function () {
            $.each(this, function (key, value) {
                switch (key) {

                    case "lat":
                        alert(value) // access to this node works fine                      
                        break;

                    default:
                        alert(value[0].geometry.location.lat) // this is undefined
                        break;
                }
            });
        });
    }
});

Anyone knows how to solve this?

Upvotes: 1

Views: 1359

Answers (2)

Kylie
Kylie

Reputation: 11749

Why not just...

$.ajax({
  type: 'GET',
  url: "http://maps.googleapis.com/maps/api/geocode/json?address=Garibaldi,Prishtina&sensor=true",
  dataType: 'json',
  success: function (data) {
       var loc = data.results[0].geometry.location;
       alert(loc.lat);
       alert(loc.lng);
        }
    });

Upvotes: 3

Ramzi Khahil
Ramzi Khahil

Reputation: 5052

You should use value.geometry... instead of value[0]. Indices are not used inside a $.each loop.

Upvotes: 2

Related Questions