大家好,我是前端开发的绝对新手,这是我第一次使用像 AngularJS 这样的东西,说实话,我认为这真的很困难,而且我对它是如何工作的也没有太多清晰的想法。我正在开发一个项目,旨在在 Google map 上可视化一批坐标。我已经在服务器端构建了相应的API并且运行良好。
我在我的项目中使用 ng-map,下面是我的 main.html 代码的第一个版本:
<div class="screen-wrapper" id="map-wrapper">
<div map-lazy-load="https://maps.google.com/maps/api/js">
<ng-map center="37.782551, -122.445368" zoom="3" disable-default-u-i="true">
<heatmap-layer id="foo" data="dummyData"></heatmap>
</ng-map>
</div>
</div>
上面的 dummyData 是一个外部 JS 文件中的硬编码数组,我最初认为这是不必要的,但后来当我尝试从 map 中获取 heatmapLayer 时,我发现这非常重要。如果没有此属性,我无法在 Controller 中获取 heatmapLayer。这有点奇怪,但我就是不知道为什么会这样。
下面是我的 main.controller.js:
(function() {
'use strict';
angular
.module('webapp')
.controller('MainController', MainController);
/** @ngInject */
function MainController(NgMap, $scope, $http) {
var resp = $http.get('url.to.api')
.then(function(result) {
return result.data;
});
var incidentData = []
var extractor = Promise.resolve(resp).then(function(data) {
for (var i = 0; i < data.length; i++) {
var lat = data[i]["lat"];
var lon = data[i]["lon"];
incidentData.push(new google.maps.LatLng(lat,lon));
}
}).then(function() {
var incidentArray = new google.maps.MVCArray(incidentData);
var heatMapLayer = new google.maps.visualization.HeatmapLayer({
data: incidentArray,
radius: 20
});
var heatmap;
$scope.$on('mapInitialized', function(event, map) {
heatMapLayer.setMap(map.instance);
});
});
}
})();
上面我尝试做的是执行 HTTP 请求来获取纬度和经度。由于它是“Promise”的格式,我必须提取它们并将其放入数组中。对我来说一切看起来都很好,但它根本不起作用。该界面仅显示“硬编码”可视化,但不显示新的 heatMapLayer。
任何人都可以建议解决我上面提到的问题的方向/解决方案吗?感谢大家和 StackOverflow。
更新根据丹尼尔的建议,我对我的代码进行了以下修改。
在 main.controller.js 中我更改了代码段:
$scope.$on('mapInitialized', function(event, map) {
heatMapLayer.setMap(map.instance);
});
至:
$scope.$apply(function() {
$scope.$on('mapInitialized', function(event, map) {
heatMapLayer.setMap(map.instance);
});
});
再次感谢丹尼尔!
最佳答案
您可能正在绕过 Angular 的摘要循环。这意味着您的更改已经完成,但尚未显示。
Angular 会自行跟踪所有更改,并在发生更改时更新 View 。每当您手动更改某些内容而不是通过 Angular 跟踪(例如通过 ng-bind 跟踪或 {{ }} 中的变量)时,您需要调用scope.$apply() 以便手动触发摘要周期。通常,当 Angular 自动执行此操作时,您甚至不会注意到(或不需要知道)。例如 $http 也会处理这个问题。
但是,这里
var resp = $http.get('url.to.api')
.then(function(result) {
return result.data;
});
我怀疑scope.$digest()在回调之后已经被调用了(当时你还没有改变任何东西)。
var extractor = Promise.resolve(resp).then(function(data) {
在第二个 .then() 回调中,您进行了更改,但它们将不再显示。
我建议将下面的代码放入第一个 .then() 回调中。如果这是不可能的,您将必须在更改完成后手动调用scope.$apply()。
关于javascript - AngularJS配合ng-map实现动态热图可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564721/