首页 > 解决方案 > 谷歌表谷歌地图API,参考错误:谷歌未定义

问题描述

我正在尝试使用以下函数映射谷歌表中两列地址之间的距离。我收到“google not defined”错误,显然是在网页上下文中使用时,尝试在页面完全加载之前访问 google 对象造成的。

为什么我在谷歌表格中收到此错误?我不允许使用相同的 API 吗?

错误是由函数抛出的getDrivingMiles

var alert = SpreadsheetApp.getUi().alert
var active_sheet = SpreadsheetApp.getActiveSheet();
var directionsService;

function onOpen()
{
  directionsService = new google.maps.DirectionsService();
  travel_mode = google.maps.DirectionsTravelMode.DRIVING;

  alert = SpreadsheetApp.getUi().alert
  active_sheet = SpreadsheetApp.getActiveSheet();
  options = [
  {
    name: "Calculate Mileage",
    functionName: "getDistanceInMiles"
  }, ];
  active_sheet.addMenu("Driving Distance", options);
}

function getColNumberByName(column_name)
{
  var whole_sheet_data = active_sheet
    .getRange("A1:1")
    .getValues();
  var col_number = whole_sheet_data[0].indexOf(column_name);
  return (col_number)
}

function getColDataByColname(column_name)
{
  var col_number = getColNumberByName(column_name);
  if (col_number != -1)
  {
    return active_sheet
    .getRange(2, col_number + 1, active_sheet.getMaxRows())
    .getValues();
  }
}

function getRangeByColname(column_name)
{
  var col_number = getColNumberByName(column_name);
  if (col_number != -1)
  {
    return active_sheet.getRange(2, col_number + 1, active_sheet.getMaxRows())
  }
}

function getDistanceInMiles()
{

  var origins = getColDataByColname('From Address');
  var destinations = getColDataByColname('To Address');
  var distance_col = getColNumberByName('Distance in Miles');
  var num_addresses = origins.length;
  var origin = "";
  var destination = "";
  var distance = 0;

  for (var i = 0; i < num_addresses; i++)
  {
    origin = origins[i][0];
    destination = destinations[i][0];
    if (origins[i][0] == "")
    {
      break;
    }
    Logger.log(origin + " to " + destination);

    var request = {
      origin: origin,
      destination: destination,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status)
    {
      if (status == google.maps.DirectionsStatus.OK)
      {
        Logger.log(response.routes[0].legs[0].distance.value); // the distance in metres
      }
      else
      {
        // oops, there's no route between these two locations
        // every time this happens, a kitten dies
        // so please, ensure your address is formatted properly
      }
    });
  }
}

function getDrivingMiles(origin, destination)
{
  Utilities.sleep(1000)
  var directions = Maps.newDirectionFinder()
  .setOrigin(origin)
  .setDestination(destination)
  .getDirections();

  if (directions && directions.error_message)
  {
    throw directions.error_message
  }

  if (directions && directions.routes && directions.routes[0] && directions.routes[0].legs && directions.routes[0].legs[0] && directions.routes[0].legs[0].distance) 
  {
    return directions
    .routes[0]
    .legs[0]
    .distance
    .value/1609.34;
  }

  return "";
}

标签: google-mapsgoogle-apps-scriptgoogle-sheets

解决方案


尽管 Google Apps 脚本是 Javascript 的子集并且共享许多功能,但它们的编程方式并不相同。也就是说,由于在您的应用程序(或默认情况下的任何 GAS 应用程序)的全局范围内没有声明“google”对象,因此在引用它时会返回错误。

为了从您的 GAS 应用程序访问 Maps API,您应该使用或者URLFetchApp甚至更好地使用受支持的内置服务。在您的情况下,这将使用Maps Service

您可以在以下链接中查看更多信息:

  • 类图。支持对服务的调用。
  • 类导向器。使用测向仪。包括对您非常有用的示例。

推荐阅读