[英]Google Maps API v3 : Passing values to Listener function(), so as to make a circle when the marker is clicked?
單擊標記時,我想在標記周圍形成一個圓圈!
因此,Listener 被添加到標記中,並且 function 需要作用於圓圈。
這是我的代碼:
for(var j=0;j<lat.length;j++)
{
var pos = new google.maps.LatLng(lat[j],lng[j]);
var marker_options = {position: pos, map:map, draggable:false};
marker[j] = new google.maps.Marker(marker_options);
circle_option = {strokeColor:"#FF0000",strokeOpacity:0.8,strokeWeight:2,fillColor:"#FF0000",fillOpacity:0.35,map:null,center:pos,radius:500};
circle[j] = new google.maps.Circle(circle_option);
google.maps.event.addListener(marker[j], 'click', function() {circle[j].setMap(map);}); // Error : circle[j] is undefined
}
錯誤:circle[j] 未定義?? (在 event.addListener 行!)
為什么..它應該在那里定義?
如何做到這一點是正確的方法? 請幫忙!
您對j
有關閉問題。 當您的 function 被調用時, j
將引用j
在 for 循環中的最后一個值。 因此, j
將lat.length
大於circle
的大小。 解決辦法是在生成回調function時強制j
被求值:
function make_callback(circle, map) {
return function() {
circle.setMap(map);
};
}
然后,在你的循環中:
google.maps.event.addListener(marker[j], 'click', make_callback(circle[j], map));
將回調生成包裝在單獨的 function 中,將在您調用make_callback
時為您提供circle[j]
的值,而不是調用回調時的值。
j
是對一個值的引用,它指向的值取決於您何時詢問j
它的值是什么。 當您像這樣綁定 function 時:
google.maps.event.addListener(marker[j], 'click', function() { something(j); });
匿名的 function 在調用 function 之前不會詢問j
它的值是多少,function 只記得它要使用j
。 當回調 function 正在執行時,它會詢問j
的當前值並使用它。 這意味着兩件事:
j
值。j
將是lat.length
,因為這是j
在循環期間分配的最后一個值。 通過使用make_callback
function 來構建回調,我們在綁定回調時詢問j
的值。 這只是一個標准技巧,當j
具有我們想要的值時強制對其進行評估。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.