2
我使用Google Maps API獲取兩點之間的距離。此方法使用回調函數。問題在於,這段代碼位於Angular服務中,我想從控制器調用該服務,以便控制器可以在範圍中輸出結果。但我不知道該服務如何將所產生的對象數組返回給控制器。我怎樣才能做到這一點?角度服務中的回調 - 如何將數據返回給控制器
myAppServices.service('NearestHospitalService', function(){
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
var hospitals = [];
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
}
else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
for (var j = 0; j < results.length; j++) {
hospitals.push(new hospital(destinations[j], results[j].distance, results[j].duration));
}
hospitals.sort(compareDistance);
}
}
});
謝謝你的幫助Magnus! 我有一個快速的問題 - 什麼是var api = {}在做什麼,你爲什麼要返回它? – bjornasm 2014-08-31 13:41:44
它使它成爲具有功能的對象。在你的例子中,根本沒有服務的返回值。 – Magnus 2014-08-31 13:44:56
謝謝。關於控制器中的功能(ds),什麼是ds? – bjornasm 2014-08-31 13:55:24