从Google Distance Matrix API获取JSON的JavaScript值

时间:2017-05-22 06:27:07

标签: javascript json google-maps google-maps-api-3

我目前正借助Google Maps Distance Matrix Api创建一个距离信息应用。以下是我的代码:

document.getElementById('generateDistance').addEventListener('click', function() {
  var origin = document.getElementById('fromLocation').value;
  var destination = document.getElementById('toLocation').value;

  var distanceUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metrics&origins=" + origin + "&destinations=" + destination + "&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

  window.location = distanceUrl;
});

它的作用是打开网址并通过JSON显示距离信息。我想要的是获取这些值,并让它显示在登录页面上。正在阅读有关解析JSON对象的内容。任何人都可以帮我理解解析吗?

1 个答案:

答案 0 :(得分:0)

您不需要让浏览器打开网址,而是需要ajax请求,以便您的脚本可以在页面上的运行时处理响应。

这只是它如何运作的一个基本例子

var xhr = new XMLHttpRequest();
xhr.open('GET', distanceUrl);
xhr.send(null);

xhr.onreadystatechange = function () {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.
  if (xhr.readyState === DONE) {
    if (xhr.status === OK) {
      plaintext = xhr.responseText;
      responseObject = JSON.parse(plaintext);
      console.log(plaintext); // 'This is the returned text.'
      console.log(responseObject) // Logs the parsed json object you can easily access properties, check the console which they are, assuming there is a property calculatedDistance you could access like:
      console.log(responseObject.calculatedDistance)
    } else {
      console.log('Error: ' + xhr.status); // An error occurred during the request.
    }
  }
};