我使用Google map API v3绘制路线。但是对于某些路径,路线不会在地图中绘制。所以我写了一个回调函数。但它不起作用,我的代码是
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() {
});
答案 0 :(得分:1)
当我将回调定义为:
时,我遇到了同样的问题function callback() {
...
}
然后我将其改为:
callback = function() {
...
}
一切正常!希望它有所帮助;)
答案 1 :(得分:0)
尝试将函数putRoute重命名为
function putRoute(request,color){}
答案 2 :(得分:0)
我猜这种情况不正确:
if (typeof callback === "function") {
我将其改为
if (typeof callback != "undefined") {
至少,我知道这最后一个代码正在运行。
你也可以尝试这个:
if (callback instanceof Function) {
// do stuff;
}
答案 3 :(得分:0)
您的回调例程位置错误。它需要位于DirectionsService的回调函数中:
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);
}
});
}