我正在尝试创建一个返回Angular JS
中热图的坐标的服务这是服务:
var traffic = angular.module('traffic', ['ngMap'])
.factory('checkpointService', function($q){
return function($scope, $http){
var d = $q.defer();
$http.get("http://127.0.0.1:8000/traffic/get/?end=" + $scope.endDateTime + "&format=json&search=Search&start=" + $scope.startDateTime)
.then(function(response) {
var points = []
angular.forEach(response.data, function(value, key) {
console.log("Response: " + JSON.stringify(response))
points.push(new google.maps.LatLng(JSON.parse(JSON.stringify(value))["lat"], JSON.parse(JSON.stringify(value))["long"]))
});
//d.resolve(points)
console.log("Points: " + points)
return points;
});
}
});
和电话:
var points = new Array();
points = checkpointService($scope, $http)
heatmap = new google.maps.visualization.HeatmapLayer({
data: points,
map: $scope.map
});
错误是"不是数组"。
我知道$ http调用是异步的,因此使用了promise。我也尝试过使用$ q.defer:
.factory('checkpointService', function($q){
return function($scope, $http){
var d = $q.defer();
$http.get("http://127.0.0.1:8000/traffic/get/?end=" + $scope.endDateTime + "&format=json&search=Search&start=" + $scope.startDateTime)
.then(function(response) {
var points = []
angular.forEach(response.data, function(value, key) {
console.log("Response: " + JSON.stringify(response))
points.push(new google.maps.LatLng(JSON.parse(JSON.stringify(value))["lat"], JSON.parse(JSON.stringify(value))["long"]))
});
d.resolve(points)
console.log("Points: " + points)
return d.promise;
});
}
});
并致电:
var points = [];
points = checkpointService($scope, $http)
points.then(function(){
heatmap = new google.maps.visualization.HeatmapLayer({
data: points,
map: $scope.map
})});
在这种情况下,错误是#34;无法读取属性'然后'未定义"。
我意识到有类似的问题;我已经阅读了它们和文档。我还在努力去理解。我知道服务中的$ http调用是成功的。但是,我相信热图数据参数中的点是空的。简单地说,服务应该为热图返回一系列LatLng点。
答案 0 :(得分:0)
通过第一种方法,你非常接近。
var traffic = angular.module('traffic', ['ngMap'])
.factory('checkpointService', function ($q) {
return function ($scope, $http) {
return $http.get("http://127.0.0.1:8000/traffic/get/?end=" + $scope.endDateTime + "&format=json&search=Search&start=" + $scope.startDateTime)
.then(function (response) {
var points = []
angular.forEach(response.data, function (value, key) {
console.log("Response: " + JSON.stringify(response))
points.push(new google.maps.LatLng(JSON.parse(JSON.stringify(value))["lat"], JSON.parse(JSON.stringify(value))["long"]))
});
//d.resolve(points)
console.log("Points: " + points)
return points;
});
}
});
checkpointService($scope, $http).then(function (points) {
heatmap = new google.maps.visualization.HeatmapLayer({
data: points,
map: $scope.map
});
});
我改变了什么: