【问题标题】:Meteor and Populating an Array with Values流星并用值填充数组
【发布时间】:2014-10-29 15:22:27
【问题描述】:

我正在玩 Meteor,但我很难理解一些概念。我目前正在处理的问题之一是我正在尝试使用 Google 和 Meteor 构建动态热图。我有一个位于我的计算机上的 Meteor Mongo 数据库(即不是 Meteor 提供的本地 MongoDB)的外部数据库,并且在数据库中我有一个包含许多文档的集合,每个文档都有一个纬度值和一个经度值。

我现在遇到的问题是,当我尝试解析我的集合中 find() 的结果集时,它没有被填充,因此我的热图值没有被绘制到屏幕上。但是,当我在控制台上运行相同的命令时,我可以获得结果。我认为代码和数据检索同时运行,并且其中一个正在击败另一个。

//Global scope
DestinationCollection = new Meteor.Collection("Destinations");
destinations = DestinationCollection.find();

if (Meteor.isClient) {

    Template.searchMap.rendered = function () {

        var airportData = [];
        var mapOptions = {
            zoom: 3,
            center: new google.maps.LatLng(45.4158, -89.2673),
            mapTypeId: google.maps.MapTypeId.HYBRID,
            mapTypeControl: false,
            panControl: false,
            streetViewControl: false
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        var airportArray = new google.maps.MVCArray([]);

        destinations.forEach(function(destination){
            airportArray.push(new google.maps.LatLng(destination.Geolocation.Latitude, destination.Geolocation.Longitude));
        });

       var heatmap = new google.maps.visualization.HeatmapLayer({
            data: airportArray,
            radius: 20
        });
        heatmap.setMap(map);
    };
}

我想出的唯一解决方案是用Deps.autorun 包装destinations.forEach

Deps.autorun(function(){
     destinations.forEach(function(destination) {
         airportArray.push(new google.maps.LatLng(destination.Geolocation.Latitude, destination.Geolocation.Longitude));
         });
});

这可行,但每当我向集合中添加新文档时,计数就会翻倍并增加 1。例如,如果我有 10 个项目,并且我向集合中添加了 1 个,则 MVCArray 将有 21 个数组元素,而不仅仅是 11 个.

长话短说,获取集合的正确方法是什么,首先解析本地集合,然后只获取添加到集合中的新值,而不是再次获取整个内容。

【问题讨论】:

    标签: javascript mongodb google-maps meteor data-visualization


    【解决方案1】:

    查看observeobserveChanges (docs) 而不是Deps.autorun

    destinations.observe({
      added: function (doc) {
        airportArray.push(new google.maps.LatLng(doc.Geolocation.Latitude, 
          doc.Geolocation.Longitude));
        // Add code to refresh heat map with the updated airportArray
      }
    });
    

    【讨论】:

    • 谢谢。我正在查看,但不是 100% 确定这是正确的路线。我做了一些更改,但是每当.observeChanges 执行时,它都会显示Exception in queued task: TypeError: Cannot read property 'Latitude' of undefined。它写了 24 次,集合中有 24 个项目,这是个好消息。我只需要弄清楚为什么doc 是未定义的。
    • 抱歉,我认为应该是observe,而不是observeChanges。无论出于何种原因,observeChangesadded 回调只是发送了一个 _id (一个字符串,所以它当然没有 Geolocation 属性),而 observeadded 回调发送的是文档对象。见docs.meteor.com/#observe
    • 非常感谢您,杰弗里·布斯。这正是我想要的。
    猜你喜欢
    • 2015-12-18
    • 2021-03-20
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多