Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript global variable not updating outside any functions

Tags:

javascript

I'm trying to get the following code to work (the console.log are just to see what's going on). I've declared the global variables outside of any functions, but it only seems to be updating them inside functions.

<script type="text/javascript">

var map;
var geocoder;
var address;

function initialize(){
    geocoder = new google.maps.Geocoder();

    var mapOptions = {
        center:new google.maps.LatLng(-76.146294, 43.052081),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 15,
        streetViewControl: false
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    loadAddress();
    console.log("initialize function: " + address); //this correctly returns the updated address
}

function loadAddress(){
    var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
    var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
    address = property + "," + zipCode;
    geocoder.geocode({'address': address}, function(result, status){
        if(status === "OK"){
            map.setCenter(result[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: result[0].geometry.location
            });
        }
        else {
            alert("Failed to geocode: " + status);
        }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

The above works fine - the 'address' variable updates properly, and when I log it to the console at the end of the initialize() function, it displays properly. The problem is if I try to log that same variable to the console further down the page:

<script type="text/javascript">
console.log("further down page: " + address); //this comes back as 'undefined'
</script>

When I try to do that, I just get 'undefined'. I'm pretty new to javascript, but my understanding was that if the variable is declared outside of any functions, it is a global variable, and it should be accessible anywhere. I feel like I'm missing something pretty obvious, but I don't know what (and I've spent quite a bit of time searching!).

My hunch is that it has to do with the initialize() not being called until after the page loads, but 'address' is trying to be logged before the page has finished loading. If that's the issue, I don't know how to fix it.

Also, I'm sure the above code is not the best way to do things, but this is really more of a learning experience. Thanks!

like image 501
falc2 Avatar asked Mar 25 '26 00:03

falc2


1 Answers

Your hunch is correct. The code further down the page is executing in place before your initialize method is called. window.load is not fired until the DOM is loaded, including images:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

A simple fix here would be to define address right away. Its components are static on the page, there's no reason to have that happen inside the function.

    var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
    var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
    var address = property + "," + zipCode;

    function loadAddress() {
      // ...
    }
like image 152
numbers1311407 Avatar answered Mar 26 '26 14:03

numbers1311407