响应式html5地理定位

Meteor.js reactive html5 geolocation position.coords

本文关键字:定位 html5 响应      更新时间:2023-09-26

我是一个meteor.js爱好者,但我确实花了相当多的时间来弄清楚这个。

我试图根据传入getCurrentPosition的HTML5地理位置API回调来主动更新我的UI。但是,UI没有更新我当前的代码。

你能提供建议和/或解决方案吗?以下是详细信息:

基础:meteor server正在运行,通过collection成功地向mongo提供其他数据

我有一个主页(main.html):

<head>
  <title>Geolocation</title>
</head>
<body>
<div class="container">
  <header class="navbar">
    <div class="navbar-inner">
      <a class="brand" href="/">Geolocation</a>
    </div>
  </header>
  <div id="locationDemo">
    {{> location}}
  </div>
</div>
</body>
引用模板(location.js)的

:

<template name="location">
  <div>
    Lat: {{lat}}
  </div>
  <div>
    Lon: {{lon}}
  </div>
</template>

有这个关联的帮助器(location.js):

_lat = {
  current: 0,
  dep: new Deps.Dependency,
  get: function(){
    this.dep.depend();
    if(this.current === 0){
      getLocation();
    }
    return this.current;
  },
  set: function(value){
    this.current = value;
    this.dep.changed();
    Deps.flush();
    return this.current;
  }
};
_lon = {
  current: 0,
  dep: new Deps.Dependency,
  get: function(){
    this.dep.depend();
    if(this.current === 0){
      getLocation();
    }
    return this.current;
  },
  set: function(value){
    this.current = value;
    this.dep.changed();
    Deps.flush();
    return this.current;
  }
};
function getLocation(){
  if (navigator.geolocation)
  {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  }
  else{
    console.log("Geolocation is not supported by this browser.");
  }
}
function showPosition(position)
{
  _lat.set(position.coords.latitude);
  _lon.set(position.coords.longitude);
}
function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      console.log("An unknown error occurred.");
      break;
  }
}
Template.location.helpers({
  lat: _lat.get(),
  lon: _lon.get()
});

据我所知,navigator.geolocation不是一个响应式数据源。因此,如果没有一些显式轮询,这将无法工作。另一个你犯的错误是你的helper不是函数,所以它们不能被反复调用。

这可能会工作(未测试):

Meteor.setInterval(function() {
    navigator.geolocation.getCurrentPosition(function(position) {
        Session.set('lat', position.coords.latitude);
        Session.set('lon', position.coords.longitude);
    });
}, 5000);
Template.location.helpers({
  lat: function() { return Session.get('lat'); },
  lon: function() { return Session.get('lon'); }
});

要使地理定位在编译为原生iOS应用的Meteor应用中工作,我需要添加可从https://atmospherejs.com/mdg/geolocation

获得的地理定位包。