Domanda

I just got some help with my geo location manager here on the forum as i ran into a dilemma. I just realised the geo location is async. where as I want it sync for easier programming. ^^

Here's the finished answer, thanks to making3: http://jsfiddle.net/x4Uf4/1/

GeoManager.prototype.init = function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(this.updateLocation.bind(this));
        } else {
            console.log("Geolocation is not activated!");
        }
    };

    GeoManager.prototype.updateLocation = function (position) {
        this.pos.lat = position.coords.latitude;
        this.pos.lng = position.coords.longitude;
    };


    var GM = new GeoManager();
    GM.init();

I've tried using $.Deferred() somehow but it just failed. Any tips? :)

È stato utile?

Soluzione

Arun P Johny answered this question in the comments.

GeoManager = function () {
    this.pos = {
        lat: 0,
        lng: 0
    };
    console.log("Geo ok...");
};

GeoManager.prototype.init = function (callback) {
    var self = this;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            self.updateLocation(position);
            callback(position);
        });
    } else {
        console.log("Geolocation is not activated!");
    }
};

GeoManager.prototype.updateLocation = function (position) {
    this.pos.lat = position.coords.latitude;
    this.pos.lng = position.coords.longitude;

    console.log(this.pos);
};

GeoManager.prototype.getLat = function () {
    return this.pos.lat;
}
GeoManager.prototype.getLng = function () {
    return this.pos.lng;
};

//returns an object
GeoManager.prototype.getPos = function () {
    return this.pos;
};

var GM = new GeoManager();
GM.init(function () {
    console.log('pos', GM.getPos())
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top