我开发了以下代码,通过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的新手。所以,如果你有任何其他想法告诉我。非常感谢:))
答案 0 :(得分: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>