Search code examples
javascriptjavascript-objectsw3c-geolocation

Javascript Objects / Geolocation API


I'm working on a mobile app with Phonegap which will use Geolocation. I used Geolocation before but this time I considered that creating a new object wrapper for it would be better as a large part of the functionality is based on this and don't want to end up with messy code.

The solution is probably straight forward but it beats me as I've never done anything very advanced in JS using objects. Here's the code (removed unneeded parts) at the moment:

function Geolocation(maximumAge, accurate) {
    this.settings = {
            'maximumAge': maximumAge,
            'accurate': accurate
    }
}

Geolocation.prototype = {
    position: {
        latitude: null,
        longitude: null,
        altitude: null,
        accuracy: null,
        altitudeAccuracy: null,
        heading: null,
        speed: null
    },
    lastCheck: null,
    watchId: null,
    onSuccess: function(position) {
        this.position.latitude = position.coords.latitude;
        this.position.longitude = position.coords.longitude;
        this.position.altitude = position.coords.altitude;
        this.position.accuracy = position.coords.accuracy;
        this.position.altitudeAccuracy = position.coords.altitudeAccuracy;
        this.position.heading = position.coords.heading;
        this.position.speed = position.coords.speed;
        this.lastCheck = new Date(position.timestamp);
    }, 
    onError: function(error) {
        console.log(error.code+' '+error.message);
    },
    getCoordinates: function() {
        if (this.watchId == null) { 
            this.watchId = navigator.geolocation.watchPosition(this.onSuccess, this.onError, { maximumAge: this.settings.maximumAge, enableHighAccuracy: this.settings.accurate});
        }
        return {
            latitude: this.position.latitude,
            longitude: this.position.longitude
        };
    }
};

As you probably noticed already, when I call getCoordinates(), the callback success function is (I'm guessing) out of the scope of the object, therefore not knowing what "this" is... Any idea of how to get around this or what the correct implementation would be?

Thank you for your time!

Later edit: I know I need to modify the function to return the coordinates only after the position was found. Not sure on how to do this at the moment, but if you have any tips that would be great!


Solution

  • OK, I figured it out, partly with help from this other thread regarding binding the scope for the callback function: JavaScript Callback Scope

    To return the coordinates I'm using a callback function. Included the code below and I'm marking this as community wiki - but if anyone has any suggestions please go ahead and make them. Everything seems to be working fine, but maybe I'm not doing something right here.

    function Geolocation(maximumAge, accurate) {
        this.settings = {
                'maximumAge': maximumAge,
                'accurate': accurate
        }
    }
    
    Geolocation.prototype = {
        position: {
            latitude: null,
            longitude: null,
            altitude: null,
            accuracy: null,
            altitudeAccuracy: null,
            heading: null,
            speed: null
        },
        lastCheck: null,
        callback: null,
        watchId: null,
        onSuccess: function(position) {
            this.position.latitude = position.coords.latitude;
            this.position.longitude = position.coords.longitude;
            this.position.altitude = position.coords.altitude;
            this.position.accuracy = position.coords.accuracy;
            this.position.altitudeAccuracy = position.coords.altitudeAccuracy;
            this.position.heading = position.coords.heading;
            this.position.speed = position.coords.speed;
            this.lastCheck = new Date(position.timestamp);
    
            var pos = {
                latitude: this.position.latitude,
                longitude: this.position.longitude
            };
                    // call callback with position and accuracy parameters
            this.callback(pos, this.position.accuracy);
        }, 
        onError: function(error) {
            console.log(error.code+' '+error.message);
        },
        getCoordinates: function(callback) {
                    // Helper function to bind scope to callback function as seen at https://stackoverflow.com/questions/183214/javascript-callback-scope
            function bind(scope, fn) {
                return function () {
                    fn.apply(scope, arguments);
                };
            }
                    // Assign the callback function to the local member
            this.callback = callback;
                    // watchPosition is a method that gets called each time the position changes. Making sure it's only getting called once (watchId can be used to stop the function when necessary
            if (this.watchId == null) {
                            // notice usage of the bind function here 
                this.watchId = navigator.geolocation.watchPosition(bind(this, this.onSuccess), bind(this, this.onError), { maximumAge: this.settings.maximumAge, enableHighAccuracy: this.settings.accurate});
            }
        }
    };
    

    Usage example:

    var geo = new Geolocation(3000, true);
    geo.getCoordinates(createMap);
    
    function createMap(position, accuracy) {
        // Your code here
    }