Я в Адвоке Обратного вызова, и я действительно не понимаю, как я уйду из него. Я пробовал читать другие темы, которые затрагивают тему, и я до сих пор не понимаю концепцию.
Я работаю с Google Maps API v3, и я пытаюсь вернуть текущую позицию пользователей, чтобы я мог передавать ее другим методам.
Мне удалось добиться успеха, используя jQuery.done() из контекста, он выдает предупреждение, но мне удается получить мой объект координат.
Если я вызываю userPosition, как я могу заставить этот метод ждать метода findUser перед возвратом переменной userPosition?
Изменение: добавлен неверный код, а после редактирования отступы отстойны. :)
userPosition: function(position)
{
if (typeof position === 'undefined')
{
//Call on findUser, when ready callback it self to set variables
}
else
{
//var userPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//return userPosition;
}
},
findUser: function()
{
var self = this;
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function(position) { // If successful
self.userPosition(position);
},
function(e) { // If something went wrong
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[e.code]);
},
{ enableHighAccuracy: true, timeout: this.timeoutVal, maximumAge: 0 }
);
}
else
{
// Set flag
}
},
Вот как я это сделал в этом jsfiddle.
var thing = {
findUser: function (callback) {
var _this = this;
// use the getPos method to get the geolocation
this.getPos(function (position) {
var lat, lng, userPos;
lat = position.coords.latitude;
lng = position.coords.longitude;
// add the new lat lng to the userPosition variable
_this.userPosition = new google.maps.LatLng(lat, lng);
// invoke the callback
callback();
});
return this;
},
getPos: function (callback) {
var geo = navigator.geolocation;
if (geo) {
// get the geolocation and pass it back to findUser
geo.getCurrentPosition(callback);
}
return this;
}
}
// if userPosition doesn't exist then grab the geolocation
if (!thing.userPosition) {
thing.findUser(function () {
console.log(thing.userPosition);
});
} else {
console.log(thing.userPosition);
}
var isUserLocationSet = false;
userPosition: function(position){
if(!isUserLocationSet)
{
settimeout(userPosition, 200);
return;
}
if (typeof position === 'undefined')
{
var userPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
return userPosition;
}
console.log(typeof position);
},
findUser: function(){
//set isUserLocationSet to true on completion in this method
var self = this;
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function(position) { // If successful
self.userPosition(position);
},
function(e) { // If something went wrong
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[e.code]);
},
{ enableHighAccuracy: true, timeout: this.timeoutVal, maximumAge: 0 }
);
}
else
{
// Set flag
}
}
Здесь вы будете проверять флаг повторно, используя setimeout и продолжая вызывать функцию до тех пор, пока не будет установлен этот флаг.
coords
?userPosition
возвращает локальную переменную, но вызовuserPosition
не использует возвращаемое значение? Вы уверены, что этот код делает то, что, по вашему мнению, делает?