且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Google Maps API v3:将值传递给Listener函数(),以便在点击标记时创建一个圆圈?

更新时间:2023-01-07 17:33:27

You have a closure problem with j. When your function is called, j will reference the last value that j had in the for loop. So, j will be lat.length which is larger than the size of circle. The solution is to force j to be evaluated when generating the callback function:

function make_callback(circle, map) {
    return function() {
        circle.setMap(map);
    };
}

and then, in your loop:

google.maps.event.addListener(marker[j], 'click', make_callback(circle[j], map));

Wrapping the callback generation in a separate function will give you the value of circle[j] at the instant when you call make_callback rather than the value when the callback is called.

j is a reference to a value, the value that it points at depends on when you ask j what its value is. When you bind a function like this:

google.maps.event.addListener(marker[j], 'click', function() { something(j); });

The anonymous function doesn't ask j what its value is until the function is called, the function simply remembers that it is going to use j. When the callback function is executing, it will ask j for its current value and use that. This means two things:

  • All the callbacks that you bound in that loop will use the same value of j.
  • j will be lat.length as that's the last value that j was assigned during the loop.

By using the make_callback function to build the callbacks, we're asking j for its value at the time that we're binding the callback. This is just a standard trick to force j to be evaluated when it has the value we want.

相关阅读

技术问答最新文章