如何从数组返回值到函数
这里我计算两个纬度和经度点之间的距离和时间。几乎我得到了答案,但我无法将该值返回给该函数。如何从数组返回值到函数
请帮帮我。在此先感谢
我的编码是:
function initMap() { console.log(getDistanceandTime(srcRouteAddress.lat,srcRouteAddress.lng,destRouteAddress.lat,destRouteAddress.lng));
function getDistanceandTime(lat1,lon1,lat2,lon2){
var origin = {lat: parseFloat(lat1), lng: parseFloat(lon1)};
var destination = {lat: parseFloat(lat2), lng: parseFloat(lon2)};
var service = new google.maps.DistanceMatrixService;
//var test = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var test_values = [];
var originList = response.originAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var test = results[j].distance.text + ' in ' + results[j].duration.text;
test_values.push(test);
console.log(test_values);
}
}
return test_values;
}
return test_values;
});
}
}
回答:
,如果它是一个同步调用,那就试试这个,你var test_values = [];
外应if (status == google.maps.DistanceMatrixStatus.OK)
条件。而最有可能的内部if (status == google.maps.DistanceMatrixStatus.OK)
不执行
也google.maps.DistanceMatrixStatus.OK
是异步的更好的内部if(google.maps.DistanceMatrixStatus.OK)
返回值,以便尝试这种
function initMap() { console.log(getDistanceandTime(srcRouteAddress.lat,srcRouteAddress.lng,destRouteAddress.lat,destRouteAddress.lng));
function getDistanceandTime(lat1,lon1,lat2,lon2){
var origin = {lat: parseFloat(lat1), lng: parseFloat(lon1)};
var destination = {lat: parseFloat(lat2), lng: parseFloat(lon2)};
var service = new google.maps.DistanceMatrixService;
//var test = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
var test_values = [];
if (status == google.maps.DistanceMatrixStatus.OK) {
var originList = response.originAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var test = results[j].distance.text + ' in ' + results[j].duration.text;
test_values.push(test);
console.log(test_values);
}
}
return test_values;
}
});
}
}
回答:
试试这个..
var test_values = []; // global variable function initMap() {
// your code here
}
function showLatLng(){
console.log(test_values); // will output the content
}
Javascript在UI线程上运行;如果您的代码等待服务器回复,则浏览器必须保持冻结状态。 Ajax jquery async return value
以上是 如何从数组返回值到函数 的全部内容, 来源链接: utcz.com/qa/266903.html