当我调用getDistanceMatrix函数时,我正在使用Google APII的DistanceMatrixService尝试传递变量'resto',这样当我得到响应时,我可以进一步使用该变量。 我的功能如下:
var service = new google.maps.DistanceMatrixService();
var resto = listRestaurant[i];
service.getDistanceMatrix({
origins: [ new google.maps.LatLng(locationCurrent.coords.latitude, locationCurrent.coords.longitude) ] ,
destinations: [ resto.address ],
//Here i am trying to pass the variable 'resto'
},function ( response , status , resto ){
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
if( response.rows[0].elements[0].distance !=null ){
//Further use variable
console.log( resto );
callGeocoder( resto );
}
}
});
但是日志返回'未定义变量'
我做错了什么?
答案 0 :(得分:0)
你没有传递变量,你定义了一个函数参数。
参数将由API内部传递,唯一将传递的参数是DirectionsResult
和DirectionsStatus
,无法传递其他参数。
您可以使用匿名函数在回调中使变量可用:
var service = new google.maps.DistanceMatrixService();
(
function(resto){
service.getDistanceMatrix({
origins: [ new google.maps.LatLng(locationCurrent.coords.latitude,
locationCurrent.coords.longitude) ] ,
destinations: [ resto.address ],
//note:travelMode is required too
travelMode: google.maps.TravelMode.DRIVING
},function ( response , status ){
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
if( response.rows[0].elements[0].distance !=null ){
//Further use variable
console.log( resto );
callGeocoder( resto );
}
}
});
}
)(listRestaurant[i]);