Using Global Variable Outside Scope of Function

Ultimately I’m attempting to get the user’s location with geolocation and then feed that location into a Google Map so that the map displays the approximate current location. My javascript seems to return latitude and longitude of the current location but I’m having trouble referencing these variables outside the scope of my javascript function. Probably a rookie mistake, but been pounding my head against the wall for some time here.

// Check to see if this browser supports geolocation.
if (navigator.geolocation) {


    // This is the location marker that we will be using on the map. Let's store a reference to it here so that it can be updated in several places.
    var locationMarker = null;
    var myLat = null;
    var myLng = null;
    var myLocation = null;


    // Get the location of the user's browser using the native geolocation service.
    navigator.geolocation.getCurrentPosition(
        function (position) {


            // Check to see if there is already a location. There is a bug in FireFox where this gets invoked more than once with a cached result.
            if (locationMarker){
                return;
            }


            // Log that this is the initial position.
            console.log( "Initial Position Found" );
            
            // Assign coordinates to global variables
            myLat = position.coords.latitude;
            myLng = position.coords.longitude;
            myLocation = myLat + ", " + myLng;
            
            // If I alert myLocation here, the coordinates are there.


        }
        
    );


}


// If I alert myLocation here, the value is null


Notice my two comments in the code. I’m attempting to alert the myLocation variable for testing. In one area, I can successfully alert the value but when I attempt to alert it in the last line of my code, the value is null. I thought that by declaring the variable outside the scope of the function would make it a global variable and usable anywhere within the window object, but clearly I’m mistaken. Any idea how I can use the value of myLocation in another function for Google Maps?

It’s not really a scope issue. It’s a timing issue. Notice that what you pass to getCurrentPosition is a callback function. The browser does some work behind the scenes to determine the location, and only when that work is done does it invoke the callback. The values are null at the last line of code because the callback hadn’t been invoked yet.

Thanks Jeff. So what’s the proper way to deal with this? The first thing that comes to mind would be to put a delay on loading the Google Map with the current coordinates, but I’d just be guessing at the timing of that delay. Is there a way to check if the callback function has yet been completed and then to initialize the Google Map?

More callbacks. :slight_smile:

// Check to see if this browser supports geolocation.
if (navigator.geolocation) {
    // This is the location marker that we will be using on the map. Let's store a reference to it here so that it can be updated in several places.
    var locationMarker = null;
    var myLat = null;
    var myLng = null;
    var myLocation = null;

    // Get the location of the user's browser using the native geolocation service.
    navigator.geolocation.getCurrentPosition(
        function (position) {
            // Check to see if there is already a location. There is a bug in FireFox where this gets invoked more than once with a cached result.
            if (locationMarker){
                return;
            }

            // Log that this is the initial position.
            console.log( "Initial Position Found" );

            // Assign coordinates to global variables
            myLat = position.coords.latitude;
            myLng = position.coords.longitude;
            myLocation = myLat + ", " + myLng;

            // If I alert myLocation here, the coordinates are there.

            [color=red]doTheNextThing();[/color]
        }
    );
}

[color=red]function doTheNextThing() {
    // If I alert myLocation here, the coordinates are there.

    // Load Google Maps
}[/color]

Thank you kindly! Seems to be working just fine now. I’ve posted my code below for somebody else that might be looking for this type of functionality.

// Check to see if this browser supports geolocation.if (navigator.geolocation) {


    // This is the location marker that we will be using on the map. Let's store a reference to it here so that it can be updated in several places.
    var locationMarker = null;
    var myLat = null;
    var myLng = null;


    // Get the location of the user's browser using the native geolocation service.
    navigator.geolocation.getCurrentPosition(
        function (position) {


            // Check to see if there is already a location. There is a bug in FireFox where this gets invoked more than once with a cached result.
            if (locationMarker){
                return;
            }


            // Log that this is the initial position.
            console.log( "Initial Position Found" );
            
            // Assign coordinates to global variables
            myLat = position.coords.latitude;
            myLng = position.coords.longitude;
            
            moveToLocation(myLat, myLng);


        }
        
    );


}


// Start the Google Maps implementation
var map;
var markersArray = [];
function initialize() {
    var mapOptions = {
        zoom: 14,
        center: new google.maps.LatLng(40.760779, -111.891047),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    
    // Add a click event handler to the map object
    google.maps.event.addListener(map, "click", function(event) {
        // Place a marker
        placeMarker(event.latLng, event.latLng.lat(), event.latLng.lng());
        
        // Display the lat/lng in your form's lat/lng fields
        //document.getElementById("lat").value = event.latLng.lat();
        //document.getElementById("lng").value = event.latLng.lng();
    });
    
    // Add a click event handler to the marker object
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent("Your content here");
        infowindow.open(map, this);
    });
    
}


function placeMarker(location, lat, lng) {
    // Remove all markers if there are any
    deleteOverlays();
    
    var marker = new google.maps.Marker({
        position: location, 
        map: map
    });
    
    // Add marker in markers array
    markersArray.push(marker);
    
    var contentString = '<a href="/post/start.php?Lat=' + lat + '&Lng=' + lng + '">New Listing</a>';
    
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    
    infowindow.open(map,marker);
    
    //map.setCenter(location);
}
    
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}


function moveToLocation(lat, lng) {
    var center = new google.maps.LatLng(lat, lng);
    map.panTo(center);
}


google.maps.event.addDomListener(window, 'load', initialize);