JS locationGet

By: | On:

  JS  

Retrieves the GPS coordinates of the Browser.

  • Uses an inline callback.
  • Normalizes the output.
  • Makes the async call feel like a sync call, but it's still async.
  • This is a good template for similar async calls.

On Github: https://github.com/campsoftware/locationGet-js

Calling Example

xanLocationGet( function ( coords ) { alert( coords[`ErrorCode`] + `, ` + coords[`ErrorDesc`] + `, ` + coords[`Latitude`] + `, ` + coords[`Longitude`] + `, ` + coords[`Altitude`] );

Function

function xanLocationGet( pCallbackFunction ) {
    // Calling Example
    // locationGet( function ( coords ) { alert( coords['ErrorCode'] + '|' + coords['Latitude'] ); } );
    if ( navigator.geolocation ) {
        navigator.geolocation.getCurrentPosition(
            function ( position ) {
                let result = {};
                result[ 'ErrorCode' ] = "0";
                result[ 'ErrorDesc' ] = "OK";
                result[ 'Latitude' ] = position.coords.latitude;
                result[ 'Longitude' ] = position.coords.longitude;
                result[ 'Altitude' ] = position.coords.altitude;
                result[ 'Heading' ] = position.coords.heading;
                result[ 'Speed' ] = position.coords.speed;
                result[ 'Accuracy' ] = position.coords.accuracy;
                result[ 'AccuracyAltitude' ] = position.coords.altitudeAccuracy;
                pCallbackFunction( result );
            },
            function ( err ) {
                let result = {};
                result[ 'ErrorCode' ] = err.code;
                result[ 'ErrorDesc' ] += ''; // err.message;
                result[ 'ErrorDesc' ] += ( err.code === 1 ) ? "The acquisition of the geolocation information failed because the page didn't have the permission to do it." : "";
                result[ 'ErrorDesc' ] += ( err.code === 2 ) ? "The acquisition of the geolocation failed. Using Safari on Mac OS? Enable System Preferences > Security and Privacy > Privacy > Location Services > Safari." : "";
                result[ 'ErrorDesc' ] += ( err.code === 3 ) ? "The time allowed to acquire the geolocation, was reached before the information was obtained." : "";
                pCallbackFunction( result );
            },
            {
                enableHighAccuracy: true,
                timeout: 15000,
                maximumAge: 0
            }
        )
    } else {
        let result = {};
        result[ 'ErrorCode' ] = -1;
        result[ 'ErrorDesc' ] = "Browser does not support Geolocation";
        callbackFunction( result );
    }
}