Search code examples
javascriptgeolocation

Accessing Variables in Javascript


I have the following code:

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } 
    else { 
        alert('Geolocation is not supported by this browser');
    }
}
function showPosition(position) {
    alert(position.coords.latitude + ' ' + position.coords.longitude);
    var Loc = position.coords.latitude + ' ' + position.coords.longitude;
}

I need to be able to access the Loc variable outside of the function or through the GetLocation Function. As i need to bind it into a grid that I am creating for storing clock on and off to work information for offsite employees.

Here is the code that uses the variable Loc

getLocation();                      
                    var rowId=timesheetGrid.uid();
                    var pos = timesheetGrid.getRowsNum();
                    timesheetGrid.addRow(rowId,["","","","<?php echo $ActiveWeek; ?>","","","","","","","","","","",Loc],0); //adds a new row with pre filled data
                    timesheetGrid.selectCell(rowId,0,false,true,true); // Focus on the new row  

Any Help would be greatly appreciated


Solution

  • navigator.geolocation.getCurrentPosition() is working in the asynchronous mode, and the function showPosition(position) is the callback function used to catch position. So you need to put all your code related to position in this callback function. For example, you can do like this:

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(whenWeGetPosition);
        } 
        else { 
            alert('Geolocation is not supported by this browser');
        }
    }
    function whenWeGetPosition(position) {
        // your code to use position
        var rowId=timesheetGrid.uid();
        var pos = timesheetGrid.getRowsNum();
        timesheetGrid.addRow(rowId,["","","","<?php echo $ActiveWeek; ?>","","","","","","","","","","",Loc],0); //adds a new row with pre filled data
        timesheetGrid.selectCell(rowId,0,false,true,true); // Focus on the new row  
    }
    
    getLocation();