2012-09-10 16 views
5

Tengo el siguiente código y crea correctamente todos los marcadores que estoy almacenando, pero cuando hago clic en cualquiera de ellos solo se crea la última ventana de información y solo aparece el último marcador sin importar en qué marcador haga clic. Me imagino que esto tiene algo que ver con la misma variable que se utiliza en mi ciclo for.Cómo crear ventanas de información para múltiples marcadores en un bucle For

{% for record in records %} 

//need to do the JSON encoding because JavaScript can't have Jinja2 variables 
//I need the safe here because Jinja2 tries to escape the characters otherwise 
var GPSlocation = {{record.GPSlocation|json_encode|safe}}; 
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ") 
var Lat = parseFloat(LatLng[0]); 
var Lng = parseFloat(LatLng[1]); 

var markerLatlng = new google.maps.LatLng(Lat, Lng); 

var marker = new google.maps.Marker({ 
    position: markerLatlng, 
    title: {{record.title|json_encode|safe}} 
}); 

var infowindow = new google.maps.InfoWindow({ 
    content: "holding..." 
    }); 

google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent({{record.description|json_encode|safe}}); 
    infowindow.open(map, marker); 
    }); 

//add the marker to the map 
marker.setMap(map); 

{% endfor %} 

He intentado cambiar el detector de eventos a esto:

google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent({{record.description|json_encode|safe}}); 
     infowindow.open(map, this); 
     }); 

Como vi que trabajaban para algunos otros usuarios de SO pero luego no hay ventanas de información se presentan. ¿Hay algún error obvio aquí?

Respuesta

5

lo necesario para crear los marcadores en una función separada:

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

y luego, dentro del bucle:

var markerLatlng = new google.maps.LatLng(Lat, Lng); 
    var title = {{record.title|json_encode|safe}} 
    var iwContent = {{record.description|json_encode|safe}} 
    createMarker(markerLatlng ,title,iwContent); 

Por último:

function createMarker(latlon,title,iwContent) { 
     var marker = new google.maps.Marker({ 
      position: latlon, 
      title: title, 
      map: map 
    }); 


google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent(iwContent); 
    infowindow.open(map, marker); 
    }); 

    } 

Explanation here.

+1

ah ese lo deja todo claro. gracias por la ayuda realmente lo aprecio – clifgray

Cuestiones relacionadas