Javascript对象和全局范围?

时间:2016-10-16 00:44:11

标签: javascript function variables javascript-objects

实际上我只想要一种方法来像以后一样访问纬度和经度全局变量。我提出了这个解决方案'如果你可以称之为。自从我做了一些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);

谢谢!

2 个答案:

答案 0 :(得分: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,因为代码段似乎不允许位置访问。

答案 1 :(得分:0)

相关问题