2011-10-04 2 views
0

J'ai un mapArray qui est créé dynamiquement en fonction des fonctionnalités clients de notre base de données.Tracer des marqueurs multiples avec plusieurs infowindows sur google maps

J'essaie de les parcourir et de créer un programme d'écoute click pour ouvrir respectivement la fenêtre d'informations de chacun.

Voici ce que j'ai jusqu'à présent

for (var i in mapArray) { 

    var thislatlng = new google.maps.LatLng(mapArray[i][1], mapArray[i][2]), 
    contentString = '<b>' + mapArray[i][6] + '</b><br /><br />' + mapArray[i][3] + '<br /><br /><a href="http://maps.google.com/maps?daddr=' + mapArray[i][3].replace("<br />", " ").replace("#", " ") + '" target ="_blank">Get Directions<\/a>', 
    marker = new google.maps.Marker({ 
     map: map, 
     position: thislatlng 
    }), 
    infowindow = new google.maps.InfoWindow({ 
     content: contentString 
    }); 

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

     infowindow.open(map, this); 
    }); 
} 

Mais le problème, c'est que tous partagent la même contentString. J'ai réussi à obtenir plus d'un problème en changeant

infowindow.open(map, marker); 

à

infowindow.open(map, this); 

Mais qui est toujours pas résoudre les problèmes de la fenêtre. Comment puis-je utiliser ouvrir infoWindow de chacun d'eux dynamiquement? Ils prennent juste la valeur du dernier.

Répondre

2

JavaScript n'a pas de portée de bloc. infoWindow est tiré vers le haut de la fonction et chaque marqueur pointe vers le même, qui est la dernière fenêtre instanciée. Vous pouvez réutiliser le même InfoWindow, en vous assurant que vous ne recevez pas plus d'un ouvert en même temps, et remplacer le contenu basé sur le marqueur cliqué:

var infowindow = new google.maps.InfoWindow(); 

for (var i in mapArray) { 

    var thislatlng = new google.maps.LatLng(mapArray[i][1], mapArray[i][2]), 
     contentString = '<b>' + mapArray[i][6] + '</b><br /><br />' + mapArray[i][3] + '<br /><br /><a href="http://maps.google.com/maps?daddr=' + mapArray[i][3].replace("<br />", " ").replace("#", " ") + '" target ="_blank">Get Directions<\/a>', 
     marker = new google.maps.Marker({ 
      map: map, 
      position: thislatlng, 
      information: contentString //Just store the string in a property 
     }); 

    google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent(this.information); //Recall the property when clicked to set the content of the window 
     infowindow.open(map, this); 
    }); 
} 

jsFiddle: http://jsfiddle.net/YCW5a/

+0

Bien obligé. .. –

Questions connexes