gpt4 book ai didi

javascript - Google Distance Matrix 需要返回值

转载 作者:行者123 更新时间:2023-11-30 12:17:34 25 4
gpt4 key购买 nike

我使用 google distance matrix api 通过以下方式获取两个地理点的最短距离:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>

var origin1 = new google.maps.LatLng(9.6667, 80.0000);
var destinationA = new google.maps.LatLng(9.6689, 80.0059);



function calculateDistances() {


var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);

}

function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;


for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
alert(results[j].distance.text);
}
}
}
}


</script>

在这段代码中,我成功地获得了最短距离。但是我需要在调用方法时返回值 calculateDistances() 而不是提醒值。我该怎么做回调方法!

最佳答案

Distance Matrix 服务是异步,因此,您需要传递一个callback 方法在请求完成时执行,以处理结果。但是您可以考虑将异步 API 转换为promises

以下示例演示了如何使用 jQuery 将距离矩阵服务 API 转换为 promise :

var origin1 = new google.maps.LatLng(9.6667, 80.0000);
var destinationA = new google.maps.LatLng(9.6689, 80.0059);



function calculateDistances(origins,destinations) {
var service = new google.maps.DistanceMatrixService();
var d = $.Deferred();
service.getDistanceMatrix(
{
origins: origins,
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
},
function(response, status){
if (status != google.maps.DistanceMatrixStatus.OK) {
d.reject(status);
} else {
d.resolve(response);
}
});
return d.promise();
}




calculateDistances([origin1],[destinationA])
.done(function(response){

var origins = response.originAddresses;

for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
//console.log(results[j].distance.text);
document.getElementById('result').innerHTML += results[j].distance.text;
}
}

})
.fail(function(status){
document.getElementById('result').innerHTML = 'An error occured. Status: ' + status;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true"></script>
<div id='result'/>

关于javascript - Google Distance Matrix 需要返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com