1

我有這個功能,我需要用響應填充結果變量。我搜索了幾個小時,但不幸的是。問題......有可能嗎?獲取或填充自定義變量與谷歌地圖方向的響應

function getRoute() { 
    var result; // array or object 

    directionsService.route(request, function(response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
     directionsRenderer.setDirections(response); 
     console.log(response.routes[0].legs[0].distance.text); 
     console.log(response.routes[0].legs[0].duration.text); 
     } 
    }); 

    return result; 
} 

結果返回作爲數組或對象

var result = getRoute(); 
    console.log(result); // anything like {'direction': 0, 'distance': 0} 

感謝建議或想法

回答

0

路線服務是異步的,它不能返回數據。如果您需要使用結果,請在回調函數中使用它。如果您稍後需要它,則可以將其分配給全局變量(或將其存儲在隱藏的輸入字段中)。

+0

嗨,謝謝你的迴應。我使用[link](http://nlaplante.github.io/angular-google-maps/#!/usage)並將導向服務實施爲指令。我需要將響應返回給控制器。我發現這篇文章[鏈接](http://stackoverflow.com/questions/13318726/easiest-way-to-pass-an-angularjs-scope-variable-from-directive-to-controller)。你認爲這可能嗎? – daremachine