Quesofat
Quesofat

Reputation: 1531

Javascript objects and the global scope?

Realistically I just want a way to access the latitude and longitude later like a global variable. I came up with this 'solution' if you can call it that. It's been a while since i've done some OOP.

What do I need to do?

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

Thanks!

Upvotes: 0

Views: 63

Answers (2)

Sreekanth
Sreekanth

Reputation: 3130

You could do something like this :

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

A working snippet is on jsFiddle, as code snippet doesn't seem to allow location access.

Upvotes: 1

Related Questions