2013-12-22 3 views
-1

Я пытаюсь получить текущее местоположение пользователя (используя geolocation.getCurrentPosition()) и сохранить его в объекте JavaScript, поэтому я могу использовать его позже.Хранение данных геоданных в объекте

Кажется, я могу хранить lat и long без проблем, но я не могу получить ни одно значение отдельно.

Вот код, который я получил:

(function() { 
    'use strict'; 

    var location = { 
     data: {}, 
     get: function() { 
      var options = { 
       enableHighAccuracy: true, 
       timeout: 5000, 
       maximumAge: 0 
      }, 
      success = function(pos) { 
       var crd = pos.coords; 
       location.data.latitude = crd.latitude; 
       location.data.longitude = crd.longitude; 
      }, 
      error = function(err) { 
       console.warn('ERROR(' + err.code + '): ' + err.message); 
      } 
      navigator.geolocation.getCurrentPosition(success, error, options); 
     } 
    }; 
    location.get(); 
    console.log(location.data); // Shows data object with current lat and long values 
    console.log(location.data.latitude); // Undefined 
}()); 

Или JSFiddle если это проще: http://jsfiddle.net/akpXM/

Любая помощь очень ценится.

ответ

1

геолокации API является асинхронным, вы должны ждать, пока результат будет возвращен

(function() { 
    'use strict'; 

    var location = { 
     data: {}, 
     get: function (callback) { 
      var self = this, 
      options = { 
       enableHighAccuracy: true, 
       timeout: 5000, 
       maximumAge: 0 
      }, 
      success = function (pos) { 
       var crd = pos.coords; 
       self.data.latitude = crd.latitude; 
       self.data.longitude = crd.longitude; 
       callback(self.data); 
      }, 
      error = function (err) { 
       console.warn('ERROR(' + err.code + '): ' + err.message); 
      } 
      navigator.geolocation.getCurrentPosition(success, error, options); 
     } 
    }; 

    location.get(function(data) { 
     // the data is only available in the callback, after the async 
     // call has completed 

     console.log(data); // Shows data object with current lat and long 
     console.log(data.latitude); // now returns the latitude 
    }); 
}()); 

FIDDLE

Смежные вопросы