Javascript 在函数中,返回值不分配给变量
我尝试使用带getMidPoint函数的多边形查找三个不同位置的三个中点。同时尝试在getMidPoint函数中返回数组。数组值没有分配给midPoints变量,我在terminal中将无法读取未定义的属性“length”作为错误Javascript 在函数中,返回值不分配给变量,javascript,arrays,node.js,express,Javascript,Arrays,Node.js,Express,我尝试使用带getMidPoint函数的多边形查找三个不同位置的三个中点。同时尝试在getMidPoint函数中返回数组。数组值没有分配给midPoints变量,我在terminal中将无法读取未定义的属性“length”作为错误 var midPoints = getMidPoint(Location1, Location2) // Directions API var i = 0; var array = []; function getMidPoint(a,
var midPoints = getMidPoint(Location1, Location2)
// Directions API
var i = 0;
var array = [];
function getMidPoint(a, b) {
console.log("I am working...")
clientMap.post(config_KEYS.DIRECTION_API + a + "&destination=" + b + "&key=" + config_KEYS.GOOGLE_API_KEY + "&departure_time=" + timeStamp + "", function (googleDirectionData, error) {
if (googleDirectionData.status == "ZERO_RESULTS" | googleDirectionData.status == "INVALID_REQUEST") {
res.status(400).send(googleDirectionData)
}
else {
var polyline = googleDirectionData.routes[0].overview_polyline.points
var decoded = decode(polyline)
var n = Math.round(decoded.length / 2)
var obj = {}
obj.latitude = decoded[n].latitude
obj.longitude = decoded[n].longitude
array.push(obj)
}
})
return array
}
if (midPoints && midPoints.length == 1) {
console.log("durationpointDat dfggdfg"+ midPoints.length)
var durationpointData2 = getMidPoint(Location2, Location3)
}
else {
if (midPoints.length == 2) {
console.log("durationpointData fdf"+ midPoints.length)
var durationpointData3 = getMidPoint(Location3, Location1)
}
else{
res.status(200).json(array)
}
}
建议将不胜感激。尝试在函数中声明var数组并返回它。不在全局范围内正如我在getMidPoint中看到的那样,您正在调用google map API。异步调用意味着在完成GoogleAPI调用之前,您的代码正在执行下一个代码,因此在中点,您将无法定义 表示在完成google map api之前返回数组。您必须创建一个回调并将数据传递给它 你可以遵循这个例子
var midPoints;
getMidPoint(Location1, Location2, function(error,data){
// You can check for error here
midPoints = data;
})
// Directions API
var i = 0;
var array = [];
function getMidPoint(a, b, callback) {
console.log("I am working...")
clientMap.post(config_KEYS.DIRECTION_API + a + "&destination=" + b + "&key=" + config_KEYS.GOOGLE_API_KEY + "&departure_time=" + timeStamp + "",
function (googleDirectionData, error) {
if (googleDirectionData.status == "ZERO_RESULTS" | googleDirectionData.status == "INVALID_REQUEST") {
res.status(400).send(googleDirectionData)
} else {
var polyline = googleDirectionData.routes[0].overview_polyline.points
var decoded = decode(polyline)
var n = Math.round(decoded.length / 2)
var obj = {}
obj.latitude = decoded[n].latitude
obj.longitude = decoded[n].longitude
array.push(obj)
callback(null, array);
}
})
}
是的,我在函数中分配了数组,但返回数组语句值未分配给中点,且中点长度未定义