从 Google Distance Matrix API 获取 JSON 的 JavaScript 值



我目前正在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;
});

它的作用是打开 url 并通过 JSON 显示距离信息。我想要的是获取这些值并将其显示在登录页面上。一直在阅读有关解析 JSON 对象的信息。任何人都可以帮助我理解解析它吗?

与其让浏览器打开 url,不如使用 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.
    }
  }
};

最新更新