10

He estado cavando por todas partes y parece que no puedo resolver esto. ¡Me esta volviendo loco! Soy un novato en javascript en general, por lo que no puedo poner un dedo en la traducción que solucionaría mi problema. Noté que mucha gente tiene este problema, pero todos parecen usar código más avanzado (o simplemente confuso) que yo. De todos modos, aquí va!Google Maps API v3 - Marcadores Todos comparten la misma ventana de información

He tenido el problema de que todos mis marcadores comparten el mismo contenido.

function initialize() { 
var myOptions = { 
    center: new google.maps.LatLng(34.151271, -118.449537), 
    zoom: 9, 
    mapTypeId: google.maps.MapTypeId.ROADMAP, 
    mapTypeControl: false, 
    streetViewControl: false, 
    panControl: false, 
    zoomControl: true, 
    zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL }, 
}; 

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

setMarkers(map, clubs); 

} 

var clubs = [ 
['Poop', 34.223868, -118.601575, 'Dookie'], 
['Test Poop', 34.151271, -118.449537, 'Test Business'] 
]; 

function setMarkers(map, locations) { 
var image = new google.maps.MarkerImage('images/image.png', 
    new google.maps.Size(25, 32), 
    new google.maps.Point(0,0), 
    new google.maps.Point(0, 32) 
); 
var shape = { 
coord: [1, 1, 1, 20, 18, 20, 18 , 1], 
type: 'poly' 
}; 
for (var i = 0; i < locations.length; i++) { 
var club = locations[i]; 
var myLatLng = new google.maps.LatLng(club[1], club[2]); 
var infowindow = new google.maps.InfoWindow(); 
var marker = new google.maps.Marker({ 
    position: myLatLng, 
    map: map, 
    icon: image, 
    shape: shape, 
    title: club[0], 
}); 
google.maps.event.addListener(marker, 'click', function(){ 
    infowindow.setContent(club[3]); 
    infowindow.open(map, this); 
}); 
} 
} 

Sé que soy malo, pero alguien por favor ayúdame! : P

Respuesta

28

El problema se debe a que está configurando el detector de eventos para que el marcador haga clic dentro de un bucle. Entonces, todos los marcadores terminan solo obteniendo el contenido para el último de sus marcadores. Prueba esto en su lugar. Crear una nueva función global:

function bindInfoWindow(marker, map, infowindow, html) { 
    marker.addListener('click', function() { 
     infowindow.setContent(html); 
     infowindow.open(map, this); 
    }); 
} 

Luego, dentro de su bucle, sustituir este:

google.maps.event.addListener(marker, 'click', function(){ 
    infowindow.setContent(club[3]); 
    infowindow.open(map, this); 
}); 

con esto:

// add an event listener for this marker 
bindInfoWindow(marker, map, infowindow, club[3]); 
+0

Gracias Duncan! Funciona muy bien y tardo 2 segundos en arreglarlo. ¡Eres el hombre! – Mikey

+0

@duncan ¡Muchas gracias! – Luftwaffe

+0

Hola chicos, esta solución también funcionó para mí, muchas gracias. Sin embargo, me gustaría entender por qué funciona de esta manera y no la otra? Todavía estamos vinculando al oyente dentro del ciclo, sin embargo, ese código ahora está envuelto en una función. ¿Por qué eso haría alguna diferencia? ¡Gracias! – WPalombini

0

Al establecer el objeto marcador (var marcador = nuevo ...) cambie esta línea: "título: club [0]," a "título: club [i],". Sí, simplemente cambie el 0 a i.

Eso debería resolver el problema.

Pruebe este enlace para obtener un tutorial sobre Google Maps API con ejemplos.

http://code.google.com/apis/maps/documentation/javascript/tutorial.html

Debe ser muy fácil y útil.

+0

cuando he intentado sustituir el '0' con 'i' se borré mi último marcador y los hice inútiles. '0' se refiere al nombre de mi marcador. – Mikey

Cuestiones relacionadas