Javascript';回调&x27;功能不工作
我使用谷歌地图API v3绘制路线。但对于某些路径,路线未绘制在地图上。所以我写了一个回调函数。但它不起作用,我的代码是Javascript';回调&x27;功能不工作,javascript,google-maps-api-3,Javascript,Google Maps Api 3,我使用谷歌地图API v3绘制路线。但对于某些路径,路线未绘制在地图上。所以我写了一个回调函数。但它不起作用,我的代码是 function putRoute(request,color,callback) { var color = color; var request = request; directionsService.route(request, function(response, status) { if (status == google.maps.Di
function putRoute(request,color,callback)
{
var color = color;
var request = request;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var polylineOptionsActual = {
strokeColor :color,
strokeOpacity: 1.0,
strokeWeight : 5,
};
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setOptions( { polylineOptions: polylineOptionsActual, suppressMarkers: true} );
directionsRenderer.setDirections(response);
}
});
if (typeof callback === "function") {
callback(request,color);
}
}
putRoute(request,color,function() {
});
尝试将函数putRoute重命名为
function putRoute(request,color){}
我猜这个条件是不正确的:
if (typeof callback === "function") {
我会改成
if (typeof callback != "undefined") {
至少,我知道最后一个代码是有效的
你也可以试试这个:
if (callback instanceof Function) {
// do stuff;
}
您的回调例程位于错误的位置。它需要位于DirectionService的回调函数中:
function putRoute(request,color,callback)
{
var color = color;
var request = request;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var polylineOptionsActual = {
strokeColor :color,
strokeOpacity: 1.0,
strokeWeight : 5,
};
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setOptions( { polylineOptions: polylineOptionsActual, suppressMarkers: true} );
directionsRenderer.setDirections(response);
// only execute callback on success
if (typeof callback === "function") {
callback(request,color);
}
} else {
alert("Directions request failed:" + status);
}
});
}
我在将回调定义为时遇到了同样的问题:
function callback() {
...
}
然后我把它改成:
callback = function() {
...
}
一切都成功了!希望有帮助;) 我想知道为什么没有绘制某些路线-这是您的数据有问题吗?我建议在“if(status==”测试中添加一个“else”,您可能会遇到错误。这为什么解决了您的问题?答案中的代码不在问题中的代码中。答案没有解释这造成的差异。