[英]Broken JS Loop with Google Maps
My code is below, and I had an issue with nearly the same code, and it was fixed here on StackOverflow, but, again, its not working. 我的代码在下面,我遇到了几乎相同的代码的问题,并在此处将其修复在StackOverflow上,但是同样,它无法正常工作。 I haven't changed the working code, but i did wrap it in the for...in
loop youll see below. 我没有更改工作代码,但是我确实将其包装在for...in
循环中,您将在下面看到。 The issue is that no matter what marker I click it always triggers the last marker/infoWindow that was placed. 问题是,无论我单击哪个标记,它始终会触发最后放置的标记/ infoWindow。
$(function(){
var latlng = new google.maps.LatLng(45.522015,-122.683811);
var settings = {
zoom: 10,
center: latlng,
disableDefaultUI:true,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
$.getJSON('api',function(json){
for (var property in json) {
if (json.hasOwnProperty(property)) {
var json_data = json[property];
var the_marker = new google.maps.Marker({
title:json_data.item.headline,
map:map,
clickable:true,
position:new google.maps.LatLng(
parseFloat(json_data.item.geoarray[0].latitude),
parseFloat(json_data.item.geoarray[0].longitude)
)
});
var infowindow = new google.maps.InfoWindow({
content: '<div><h1>'+json_data.item.headline+'</h1><p>'+json_data.item.full_content+'</p></div>'
});
new google.maps.event.addListener(the_marker, 'click', function() {
infowindow.open(map,the_marker);
});
}
}
});
});
Thank you for whoever figures this out! 感谢您解决这个问题的人!
What's going on is that when you create each of your event handler closures (functions): 这是在创建每个事件处理程序闭包(函数)时的情况:
new google.maps.event.addListener(the_marker, 'click', function() {
infowindow.open(map,the_marker);
});
...they each get an enduring reference to the variable the_marker
, not its value at the moment the closure is created. ...每个变量都获得对变量the_marker
的持久引用, 而不是创建闭包时的值。 So all copies of that closure function use the same value (the last value assigned to it in the loop). 因此,该闭包函数的所有副本都使用相同的值(循环中分配给它的最后一个值)。 Closures are not complicated ( more here ), but let's just say you're not the first person to make this mistake. 关闭并不复杂( 更多信息请参见此处 ),但是我们只能说您不是第一个犯此错误的人。 :-) It's very easy to do. :-)这很容易做到。
So what you want to do is capture the value of the_marker
as of that loop iteration, which is easily done: 因此,您想要做的就是在循环迭代中捕获the_marker
的值 ,这很容易做到:
new google.maps.event.addListener(
the_marker,
'click',
buildHandler(map, the_marker));
function buildHandler(map, marker) {
return function() {
infowindow.open(map, marker);
};
}
There, we have a function that builds the handler using the arguments passed into the function, and we call that function on each loop iteration to create our handler for us. 那里,我们有一个函数,该函数使用传递给函数的参数构建处理程序,并在每次循环迭代时调用该函数为我们创建处理程序。
This answer to another question on SO may help you visualize how closures get access to variables. 对SO另一个问题的这个答案可能有助于您直观地了解闭包如何访问变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.