如何使用meteor自动更新传单地图上的标记

时间:2013-03-08 10:27:05

标签: javascript meteor leaflet

对于一个学校项目,我们有这个想法来制作一个地理空间标签游戏。您登录我们的应用程序,您的位置显示在地图上,每当您接近其他玩家时,您都会标记该人。 (就像孩子的标签,但有流星)

我们遇到的问题,我们似乎无法在传单地图上自动更新我们的标记。有一个标记显示它没有更新。

我们尝试过使用Player.update,但它不起作用。

有什么建议吗?

代码

     if (Meteor.isClient) {

    var userLatitude;
    var userLongitude;

    var map;

    Template.map.rendered = function () {

        // Setup map
        map = new L.map('map', {
            dragging: false,
            zoomControl: false,
            scrollWheelZoom: false,
            doubleClickZoom: false,
            boxZoom: false,
            touchZoom: false
        });

        map.setView([52.35873, 4.908228], 17);
        //map.setView([51.9074877, 4.4550772], 17);

        L.tileLayer('http://{s}.tile.cloudmade.com/9950b9eba41d491090533c541f170f3e/997@2x/256/{z}/{x}/{y}.png', {
            maxZoom: 17
        }).addTo(map);

        // If user has location then place marker on map
        if (userLatitude && userLongitude) {
            var marker = L.marker([userLatitude, userLongitude]).addTo(map);
        }

        var playersList = players.find().fetch();
        playersList.forEach(function(players) {
            // Change position of all markers
            var marker = L.marker([players.latitude, players.longitude], options={"id" : 666}).addTo(map);
        });
    };

    // If the collection of players changes (location or amount of players)
    Meteor.autorun(function() {

        var playersList = players.find().fetch();
        playersList.forEach(function(players) {
            // Change position of all markers
            var marker = L.marker([players.latitude, players.longitude]).addTo(map);
        });
    });
}



if (Meteor.isServer) {
    Meteor.startup(function () {
        // code to run on server at startup

    });
}











    /*
Template.hello.events({
        'click input' : function () {
        // template data, if any, is available in 'this'
        if (typeof console !== 'undefined')
            console.log("You pressed the button");
        }
    });
*/

/*
if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {                   
                userLatitude = 52.35873;
                userLongitude = 4.908228;

                players.insert({
                    name: "Martijn",
                    latitude: userLatitude,
                    longitude: userLongitude
                });
            });
        }
*/

1 个答案:

答案 0 :(得分:9)

您需要清除现有标记,否则它们会保留在地图上。最简单/最有效的方法是在创建时将标记附加到LayerGroup。然后,当您想要更新时,清除所有标记,然后再次添加它们。

在顶部添加图层组声明,因此您有

var map, markers;

初始化地图后,

markers = new L.LayerGroup().addTo(map);

更改此行:

var marker = L.marker([userLatitude, userLongitude]).addTo(map);

为:

var marker = L.marker([userLatitude, userLongitude]).addTo(markers);

在你的自动运行中,在forEach之前,

markers.clearLayers();

然后在你的foreach中,

var marker = L.marker([players.latitude, players.longitude]).addTo(markers);
相关问题