javascript - 多个目的地谷歌距离矩阵api
问题描述
我正在使用谷歌区别矩阵来计算 3-4 个不同地址之间的行驶时间。我已经成功获得了 2 个地址(一个起始地址和一个目标地址)的结果但是当我想计算超过 2 个地址的总驱动距离时,我读过你可以传递多个地址的数组,如下所示. 但我收到此错误消息
Uncaught ReferenceError: google is not defined
at calculateDistance (5c1361804fdab94f5e63ba42:1572)
at HTMLDocument.<anonymous> (5c1361804fdab94f5e63ba42:2479)
at c (vendors.bundle.js:1)
at h (vendors.bundle.js:1)
产生此错误的代码
// calculate distance
function calculateDistance() {
debugger;
var origin = ["Frimurarvägen, Skärholmen, Sverige", "Hanstavägen 55 F, 164 53 Kista, Sverige"];
var destination = ["Axbergsgränd 31, 124 66 Bandhagen, Sverige"];
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
// get distance results
function callback(response, status) {
debugger;
if (status != google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
} else {
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
$('#result').html("Better get on a plane. There are no roads between " + origin + " and " +
destination);
} else {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
console.log(response.rows[0].elements[0].distance);
var distance_in_kilo = distance.value / 1000; // the kilom
var distance_in_mile = distance.value / 1609.34; // the mile
var duration_text = duration.text;
var duration_value = duration.value;
$('#in_mile').text(distance_in_mile.toFixed(2));
$('#in_kilo').text(distance_in_kilo.toFixed(2));
$('#duration_text').text(duration_text);
$('#duration_value').text(duration_value);
$('#from').text(origin);
$('#to').text(destination);
}
}
}
我试图像这样删除原始数组上的第二个索引
var origin = ["Frimurarvägen, Skärholmen, Sverige"];
尝试它是否甚至可以带一个数组。然后我得到这个错误响应。
InvalidValueError: in property origins: at index 0: not a string; and not a LatLng or LatLngLiteral: in property lat: not a number; and unknown property 0
我怎样才能以正确的方式做到这一点?我也许应该做一个 foreach 循环并为每个目的地/来源做多个 google api 请求?或者有没有办法做到这一点,我在代码中尝试的方式可能是我错过了什么?
使用googles direction api来获取几个地址/一条路线的总区别时间会更好吗?
解决方案
推荐阅读
- react-native - 调用 Woocommerce api 进行本机反应
- android - 在android中安排通知
- java - 使用 Java Stream 根据第二个列表中的值过滤列表
- vulkan - 关于多个顶点类型和多个着色器的基本问题
- git-stash - 是否可以存放暂存区,但不能存放工作树?
- javascript - 尝试将代码注入 Microsoft Teams 时出错
- python - 如何在解码为 [UNK] bert tokenizer 的 vocab.txt 中添加标记
- python - 我设置 evaluate=False,买 SymPy 的 parse_expr 仍然计算表达式
- javascript - 如何手动发出事件到间隔?
- c# - 在 MainWindow C# WPF 中显示结果