【问题标题】:Get JavaScript value of JSON from Google Distance Matrix API从 Google 距离矩阵 API 获取 JSON 的 JavaScript 值
【发布时间】:2017-05-22 06:27:07
【问题描述】:

我目前正在 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 对象的内容。任何人都可以帮助我理解它的解析吗?

【问题讨论】:

  • 您需要使用 Ajax 获取请求来获取响应..我已经为您创建了一个小提琴来演示..您必须在那里设置您的 api 密钥..jsfiddle.net/z32u6f2L
  • @talentedandrew 但这需要 jQuery,对吧?我实际上是想把它纯粹放在 JavaScript 上。我已经阅读了可以通过处理 JSON 来完成的文档,但我无法理解,所以我来到了这里。这是参考的链接 - link
  • 您必须执行 ajaxcall,以便您的运行时能够接收和解析 json 数据,使用纯 js 执行这些请求没有问题,只需搜索 vanilla ajax 或 javascript xhr,如果您收到数据你可以像json一样访问它#

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


【解决方案1】:

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

这只是它如何工作的一个基本示例

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.
    }
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2012-03-27
    • 1970-01-01
    • 2012-04-11
    • 2018-08-15
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多