2016-01-06 244 views
1

我开发了下面的代码,通过2个文本区域来获得给定2个城市的距离,并且我想使用以下URl将它们发送到谷歌地图距离矩阵api。我发送这些城市并获得JSON输出文件。但我的问题是如何从该JSON文件中获取特定属性(距离)并在另一个文本字段上显示。使用谷歌地图距离矩阵api得到距离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的新手。所以,如果你有任何其他想法告诉我。非常感谢:)

回答

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/

+0

非常感谢。有效 :))) – sheslv