-2

我正在尝试从 Google 地图提供的 JSON 访问持续时间数据。用户输入 2 个邮政编码,我应该显示所用时间。

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);
}

这是我的 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>

我安慰了生成的 URL,当打开它时,它给出了正确的 JSON 对象。

4

1 回答 1

0

FIDDLE 返回的 786

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

您需要在回调函数my_json内部使用getJSON

于 2013-04-10T18:30:07.610 回答