2013-04-29 88 views
2

我在這裏的問題是,功能google.maps.event.addListener(marker, 'click', (function()的作品,然後我點擊第一個標記。點擊所有其他標記不起作用。我希望這個函數能夠處理所有的標記。這裏有什麼問題?功能只適用於1標記

var marker, i; 

for (i = 0; i < locations.length; i++) { 
    marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
     map: map, 
    }); 

    google.maps.event.addListener(marker, 'click', (function (marker, i) { 
     return function() { 
      MyApp.xxx = this.position; 
      infowindow.setContent('x' + name[i][3] + '' + name[i][4] + 'x'); 
      infowindow.open(map, marker); 
     } 
    })(marker, i)); 
} 

var markerroad; 

google.maps.event.addListener(marker, 'click', (function() { 

    var request = { 
     origin: MyApp.xxx, 
     destination: 'Kaunas', 
     travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 

    directionsService.route(request, function (response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
      directionsDisplay.setDirections(response); 
     } 
    }) 
})); 
+0

其他標記是否存在加載或他們添加後?如果是這樣,你需要'.on('click')'而不是'.click()',它只綁定運行時存在的節點。 – hexblot 2013-04-29 14:26:35

+0

除了上面的代碼外,沒有更多的代碼可用於生成標記。 – user1876234 2013-04-29 14:29:47

+1

爲什麼你的'for'循環之外的第二個'google.maps.events.addListener'? – Ian 2013-04-29 14:38:37

回答

1

您不在循環中包含第二個addListener。試試這個:

var marker, i; 

for (i = 0; i < locations.length; i++) { 
    marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
     map: map, 
    }); 

    google.maps.event.addListener(marker, 'click', (function (marker, i) { 
     return function() { 
      MyApp.xxx = this.position; 
      infowindow.setContent('x' + name[i][3] + '' + name[i][4] + 'x'); 
      infowindow.open(map, marker); 
     } 
    })(marker, i)); 

    google.maps.event.addListener(marker, 'click', function() { 
     var request = { 
      origin: MyApp.xxx, 
      destination: 'Kaunas', 
      travelMode: google.maps.DirectionsTravelMode.DRIVING 
     }; 

     directionsService.route(request, function (response, status) { 
      if (status == google.maps.DirectionsStatus.OK) { 
       directionsDisplay.setDirections(response); 
      } 
     }); 
    }); 
} 

由於兩個addListener電話是同一項目(),你很可能在每個功能結合的代碼,這樣,只有一個addListener電話。