Justin Homes
Justin Homes

Reputation: 3799

Parse Google Map Json with Jquery

I have a google Mpa Json url http://maps.googleapis.com/maps/api/distancematrix/json?&origins=2020%20E%20main%20ST&destinations=100%20E%20Main%20St%20,Edmond,Ok&mode=driving&sensor=false

that gives me

{
   "destination_addresses" : [ "100 East Main Street, Edmond, OK 73034, USA" ],
   "origin_addresses" : [ "2020 East Main Street, Lamar, AR 72846, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "410 km",
                  "value" : 409567
               },
               "duration" : {
                  "text" : "3 hours 49 mins",
                  "value" : 13759
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

i am trying to parse it using

  function callGoogle(inputOrigin, inputDst, inputMode)
      {
      $.getJSON('http://maps.googleapis.com/maps/api/distancematrix/json?', { origins: inputOrigin, destinations: inputDst, mode: inputMode,  sensor: false }, function (data) {

                $.each(data, function (i, item) {               
                    console.log(item.rows.elements.distance.text);

                });


            });

        }

but i am getting erros. how do i get the 97.8 or 97766 from this json using jquery

Upvotes: 2

Views: 1414

Answers (1)

Steve Wellens
Steve Wellens

Reputation: 20620

Do you mean like this?

var data = {
    "destination_addresses": ["1000 Chopper Circle, Denver, CO 80204, USA"],
    "origin_addresses": [
        "2121 East Mulberry Street, Fort Collins Nursery, Fort Collins, CO 80524, USA"
    ],
    "rows": [
        {
            "elements": [
                {
                    "distance": {
                        "text": "97.8 km",
                        "value": 97766
                    },
                    "duration": {
                        "text": "57 mins",
                        "value": 3449
                    },
                    "status": "OK"
                }
            ]
        }
    ],
    "status": "OK"
};

alert(data.rows[0].elements[0].distance.value);

Note, the data has two arrays, I am using [0] to get the first item in each.

Upvotes: 4

Related Questions