开发者

Variable Undefined after jQuery Change

var circle = new google.maps.Circle({
    center: latLng,
    radi开发者_高级运维us: 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜