ATLChris
ATLChris

Reputation: 3296

Variable Undefined after jQuery Change

var circle = new google.maps.Circle({
    center: latLng,
    radius: radius,
    strokeColor: "#FF0000",
    strokeOpacity: 0.5,
    strokeWeight: 1,
    fillColor: "#FF0000",
    fillOpacity: 0.2
});

circle.setMap(map);

map.fitBounds(circle.getBounds());

jQuery('#area').change(function() {
    radius = jQuery('#area').val();

    var newLatLng = marker.getPosition();

    circle.setMap(null);

    var circle = new google.maps.Circle({
        center: latLng,
        radius: radius,
        strokeColor: "#FF0000",
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: "#FF0000",
        fillOpacity: 0.2
    });

    circle.setMap(map);

    map.fitBounds(circle.getBounds());
});

circle is defined outside the jQuery('#area').change() but when I try to access it from inside the jQuery('#area').change() function, I get an undefined error. Why is this?

Upvotes: 1

Views: 501

Answers (2)

jimbo
jimbo

Reputation: 11042

Because your inner function contains var circle. Due to a phenomenon known as "var hoisting", the entire function considers circle to be a local variable, even though the var statement appears later.

Name your inner function's circle something else.

Upvotes: 3

jfriend00
jfriend00

Reputation: 708026

Inside your .change function, change this line:

var circle = new google.maps.Circle({

to this:

circle = new google.maps.Circle({

The way you had it, you were creating a new local variable named circle and setting it's value and you were not setting the value of the global defintion of circle. Then, when you come in the next time and call circle.setMap(null) on the global one, it's still null.

So, if you only mean to be operating on the global definition of circle, then remove the var as above in the .change() function. If you meant to create a new temporary circle object for use only during that .change() function that would not survive past the execution of that function, then name that local copy something other than circle.

Upvotes: 1

Related Questions