1

我开发了以下代码以通过 2 个文本字段获取给定 2 个城市的距离,我想使用以下 URl 将它们发送到谷歌地图距离矩阵 api。我发送这些城市并获得 JSON 输出文件。但我的问题是如何从该 JSON 文件中获取特定属性(距离)并显示在另一个文本字段上。

function m() {

            var x = document.getElementById("autocomplete").value;
            var y = document.getElementById("autocomplete1").value;

            var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + x + "&destinations=" + y + "&key=AIzaSyD5KX6VRon6yQ0vu4s6GSnAVzazRWg8wrc";

window.location=url; // this will go to the above url and display the JSON output file on the browser. I dont want that to be shown. just some processing and should display only the distance form that file on a textfield!

}

JSON 输出文件http://pastebin.ca/3318529

请帮助解决这个问题。我是 JSON 新手。因此,如果您有任何其他想法,请告诉我。非常感谢 :)

4

1 回答 1

1

如果您在浏览器中使用 Javascript,则需要使用 Google Maps Api。

检查这个例子:

<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function init() {
  var service = new google.maps.DistanceMatrixService;
  service.getDistanceMatrix({
    origins: ['Los Angeles'],
    destinations: ['New York'],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status) {
    if (status !== google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      alert(response.originAddresses[0] + ' --> ' + response.destinationAddresses[0] + ' ==> ' + response.rows[0].elements[0].distance.text);
    }
  });
}
</script>
<body onload="init()">
</body>

运行示例https://jsfiddle.net/3b03m5mt/

于 2016-01-06T02:58:42.130 回答