当用户在Meteor中提交帖子时,我如何有效地存储用户的位置

How do I effectively store position of users when they submit a post in Meteor?

本文关键字:用户 有效地 存储 位置 Meteor 提交      更新时间:2023-09-26

我使用mdg: geoocation包。我试图在他或她提交消息的那一刻存储用户的位置。


在postSubmit.js(客户端)中:

Template.postSubmit.events({'submit form': function(e) {e.preventDefault();
    var post = {
      message:  $(e.target).find('[name=message]').val(),
      loc: {
        type:"Point",
        coordinates: [82.1, 55.4] //fake data 
      }
    };

还需要行来检索用户提交消息时的当前位置。

Template.postSubmit.onCreated(function() {  
  'loc': function() {                     //doesnt work, identifier error
      Session.set("loc", Geolocation.latLng());
  },

我看到了兜售这个版本的例子,但它给了我错误流星定位方法从事件

我的问题是1. 我如何替换假数据更新与检索{lng, lng}?2. 将模板。on渲染的例子是有效的?

如果您只在发布消息时需要它,则无需将其存储在会话中。你只需要在提交事件中获取它。

Template.postSubmit.events({'submit form': function(e) {e.preventDefault();
  var loc = Geolocation.latLng();
    var post = {
      message:  $(e.target).find('[name=message]').val(),
      loc: {
        type:"Point",
        coordinates: [loc.lng, loc.lat]
      }
    };
    Meteor.call('postInsert', post, function (err, res) {
      if (!err)
        console.log("inserted!");
    });
  }
});

如果您希望地理位置在整个发布过程中可用,最简单的方法是使用轮询和会话变量:

Template.postSubmit.onCreated(function() {  
  this.interval = Meteor.setInterval(function () {
    Session.set('location', Geolocation.latLng());
  }, 2000); // get location every 2 seconds
});
然后,您可以使用模板帮助器检索它:
Template.postSubmit.helpers({  
  'loc': function () {
    return Session.get('location');
  }
});

您可以在完成post提交时停止间隔:

Template.postSubmit.events({'submit form': function(e, t) {
  e.preventDefault();
  var loc = Session.get('location');
    var post = {
      message:  $(e.target).find('[name=message]').val(),
      loc: {
        type:"Point",
        coordinates: [loc.lng, loc.lat]
      }
    };
    Meteor.call('postInsert', post, function (err, res) {
      if (!err) {
        Meteor.clearInterval(t.interval);
        console.log("inserted!");
      }
    });
  }
});