簡體   English   中英

在全局助手(流星)中設置地理位置

[英]Set geolocation in a global helper (Meteor)

我嘗試在助手中設置地理位置信息。 我使用以下軟件包:

mdg:geolocationaldeed:geocoder

這是我的幫手:

Template.registerHelper("geo", function () {
  var geo = Geolocation.latLng() || { lat: 0, lng: 0 };

  if(geo.lat !== 0){
    var infos = Meteor.call('locationName', geo.lat, geo.lng, function(err, res){
        return res[0];
    });
  }
});

這是返回的對象

在此處輸入圖片說明

這是我的服務器呼叫

Meteor.methods({
  locationName: function(lat, lng){
  console.log(lat, lng);
  var geo = new GeoCoder({
    geocoderProvider: configs.geocoder.geocoderProvider,
    httpAdapter: configs.geocoder.httpAdapter,
    apiKey: configs.geocoder.apiKey
  });

  var reverseGeocoding = geo.reverse(lat, lng);

  return reverseGeocoding;
}
});

我嘗試了很多事情,但是我的{{geo.city}}總是空着。 我如何正確構造它?

謝謝

您正處於助手中典型的方法調用問題中。 查看您的模板助手的代碼。 它基本上是這樣做的:

Template.registerHelper("geo", function () {
  // inside helper
  // doing some stuff...
  Meteor.call('someMethod', function(err, res){
    // Other scope!
    console.log("Toto, I've a feeling we're not in the `geo` helper any more.");
    return res; // returning this to nowhere
  });
  // back inside helper
  return undefined; // returns before the above callback even triggers
});

問題在於,您不能從方法調用的回調中返回某些內容,並且不能期望從您調用該方法的幫助程序返回該值:它們是不同的作用域,因為方法調用是異步的。 您可以執行以下操作:

Template.registerHelper("geo", function () {
  return Session.get('locationName');
});

updateLocationName = function (geo) {
  return Meteor.call('locationName', geo.lat, geo.lng, function(err, res){
        Session.set('locationName', res[0]);
  });
}

if (Meteor.isClient) {
  Meteor.startup(function () {
    var geo = Geolocation.latLng() || { lat: 0, lng: 0 };
    Session.setDefault('locationName', null);
    if(geo.lat !== 0){
      var infos = updateLocationName(geo);
    }
  });
}

如果要更新會話變量(例如在onRenderedautorun中),則只需使用更新的Geolocation.latLng()對象調用updateLocationName()

我做到了,但也許它有更好的方法。 謝謝您的回答! 有我的密碼

Template.registerHelper("geo", function () {

if(Session.get('geolocation') === null){
    var geo = Geolocation.latLng() || { lat: 0, lng: 0 };

    if(geo.lat !== 0){
        Meteor.call('locationInfos', geo.lat, geo.lng, function(err, res){
            Session.set('geolocation', res[0]);
        });
    }
}

return Session.get('geolocation');

});

我在Meteor.startup中將會話變量設置為NULL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM