Я пытаюсь отобразить расстояние между двумя столбцами адресов в листе Google, используя функции ниже. Я получаю сообщение об ошибке "Google не определен", которое, по-видимому, при использовании в контексте веб-страницы возникает в результате попытки доступа к объекту Google до полной загрузки страницы.
Почему я получаю эту ошибку в 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 "";
}