【问题标题】:Javascript objects and the global scope?Javascript对象和全局范围?
【发布时间】:2016-10-16 00:44:10
【问题描述】:

实际上,我只是想要一种以后像全局变量一样访问纬度和经度的方法。如果你可以这样称呼它,我想出了这个“解决方案”。自从我做了一些 OOP 以来已经有一段时间了。

我需要做什么?

var geo = {

   local: function() {
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(postition){
      latitude: position.coords.latitude;
      longitude: position.coords.longitude;
    })
  }
}
};

function initMap() {
  var userLocation = {lat: geo.local.latitude, lng: geo.local.longitude};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom:14,
    center: userLocation
  });
};

console.log(geo.local.longitude);
console.log(geo.local.latitude);

谢谢!

【问题讨论】:

    标签: javascript function variables javascript-objects


    【解决方案1】:

    你可以这样做:

    var geo = {
      local: {
        longitude: "",
        latitude: "",
        positionFound: false
      },
      location: (function() {
    
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            geo.local.latitude = position.coords.latitude;
            geo.local.longitude = position.coords.longitude;
            geo.local.positionFound = true;
          });
        }
      })()
    };
    
    function initMap() {
      var userLocation = {
        lat: geo.local.latitude,
        lng: geo.local.longitude
      };
      if (geo.local.positionFound) {
        console.log(userLocation.lat + " - " + userLocation.lng);
      } else {
        console.log("Location Not found");
      }
    };
    
    setTimeout(function() {
      initMap();
    }, 5000);

    jsFiddle 上有一个工作的 sn-p,因为代码 sn-p 似乎不允许位置访问。

    【讨论】:

    • 如果你能快速引导我完成它,我会很高兴的!
    • 基本上,如果地理定位 API 只是一种同步方法,这将是一个简单的解决方案。由于 getCurrentPosition 是一个异步方法。我们确实需要等待方法完成并执行成功回调。所以有人必须调用 Async api,这就是 IIFE 派上用场的时候。他们在声明后立即调用该方法。 geo.location 是 IIFE 的一个例子。但是根据您的要求,您希望 position 作为变量可用,我们需要在我们可以访问的一些属性中更新它们。
    • 因此是 geo.local。此外,我们需要确保位置已正确填充,我们需要确保 getCurrentPosition 成功执行,因此使用 locationFound 作为看门人,以确保我们拥有正确的位置值。当您只想在找到位置值时才执行某些操作时,这可能很方便。在你的情况下,创建谷歌地图对象。
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多