-2

I am trying to access the duration data from the JSON provided by Google maps. The user enters 2 postcodes and the I am supposed to display time taken.

function getData() {
    var origin = $("#origin_pc").val() + ",australia";
    var destination = $("#dest_pc").val() + ",australia";
    // var origin="3135,australia";
    // var destination="3155,australia";
    url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
    return url;
}

function calculateDistance() {
    // console.log(getData());
    var my_json;
    $.getJSON(getData(), function (json) {
        my_json = json;
    });
    console.log(my_json.routes[0].legs[0].duration.value);
}

Here is my HTML

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>

    <body>
        <form>
            <input type="text" id="origin_pc" />
            <input type="text" id="dest_pc" />
            <input type="submit" onclick="calculateDistance();">
        </form>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript" src="distance.js"></script>
    </body>
</html>

I consoled the resulting URL and when opened, it gave the correct JSON object.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
hirani89
  • 156
  • 1
  • 2
  • 13

1 Answers1

0

FIDDLE return's 786

$.getJSON(getData(), function(json) {
   my_json = json;
   $('body').text(my_json.routes[0].legs[0].duration.value);
});

You need to use my_json inside of getJSON callback function

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111