Metoer地理定位获取城市州和国家/地区名称

时间:2015-09-19 04:09:24

标签: javascript meteor geolocation

我有一个获得经度和纬度的代码,我很难理解如何获取当前的地理位置并自动显示它。我想获得城市,州名

下面是代码

<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>
<template name="location">
  <div>
    Lat: {{lat}}
  </div>
  <div>
    Lon: {{lon}}
  </div>
</template>

的javascript

    _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;
  }
}

  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'); }
  });

meteorpad上的代码

http://meteorpad.com/pad/oR9aL3E2TSYFjjHGH/Leaderboard

0 个答案:

没有答案