33

Quiero abrir una nueva ventana haciendo clic en un marcador usando Google Maps API 3.API de Google Maps: Abrir URL haciendo clic en marcador

Desafortunadamente no hay muchos ejemplos de la API de Google Maps y descubrí este código:

google.maps.event.addListener(marker, 'click', function() { 
    window.location.href = marker.url; 
}); 

¿Cómo usarlo cuando creo marcadores con un bucle? Lo intenté de muchas maneras sin ningún costo.

Este es mi código - lo hice simple y corto:

<!DOCTYPE html> 
<html> 
<head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 

    <style type="text/css"> 
     html { height: 100% } 
     body { height: 100%; margin: 0; padding: 0 } 
     #map_canvas { height: 100% } 
    </style> 

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 

    <script type="text/javascript"> 
    var points = [ 
     ['name1', 59.9362384705039, 30.19232525792222, 12], 
     ['name2', 59.941412822085645, 30.263564729357767, 11], 
     ['name3', 59.939177197629455, 30.273554411974955, 10] 
    ]; 

    function setMarkers(map, locations) { 
     var shape = { 
      coord: [1, 1, 1, 20, 18, 20, 18 , 1], 
      type: 'poly' 
     }; 

     for (var i = 0; i < locations.length; i++) { 
      var flag = new google.maps.MarkerImage('markers/' + (i + 1) + '.png', 
      new google.maps.Size(17, 19), 
      new google.maps.Point(0,0), 
      new google.maps.Point(0, 19)); 

      var place = locations[i]; 
      var myLatLng = new google.maps.LatLng(place[1], place[2]); 
      var marker = new google.maps.Marker({ 
       position: myLatLng, 
       map: map, 
       icon: flag, 
       shape: shape, 
       title: place[0], 
       zIndex: place[3] 
      }); 
     } 
    } 

    function initialize() { 
     var myOptions = { 
      center: new google.maps.LatLng(59.91823239768787, 30.243222856188822), 
      zoom: 12, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); 
     setMarkers(map, points); 
    } 
    </script> 
</head> 

<body onload="initialize()"> 
    <div id="map_canvas" style="width:50%; height:50%"></div> 
</body> 
</html> 

¿Cómo abrir URL haciendo clic en marcador con el código de seguridad?

Respuesta

75

Usted puede añadir una URL específica para cada punto, por ejemplo:

var points = [ 
    ['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'], 
    ['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'], 
    ['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com'] 
]; 

añadir la URL a los valores de los marcadores en el bucle for:

var marker = new google.maps.Marker({ 
    ... 
    zIndex: place[3], 
    url: place[4] 
}); 

continuación, puede añadir justo antes de que el final de su ciclo for:

google.maps.event.addListener(marker, 'click', function() { 
    window.location.href = this.url; 
}); 

Ver también example.

+0

Gracias por responder. De esta forma, se abre la última url para cada marcador. Intenté esto y no encontré la manera de solucionarlo. Verifiqué tu ejemplo (enlace arriba): hasta donde puedo juzgar: existe el mismo problema: cuando haces clic en el marcador, aparece un "enlace stackoverflow" para cada marcador. – idobr

+0

Lo sentimos, tienes razón, he actualizado mi respuesta. – scessor

+0

¡Eso es realmente genial! Funciona. Pensé que el problema era con un lugar equivocado para el oyente. Muchas gracias. – idobr

4

url no es un objeto en la clase Marker. Pero no hay nada que te impida agregar eso como propiedad de esa clase. Supongo que cualquier ejemplo que estuvieras mirando hizo eso también. ¿Quieres una URL diferente para cada marcador? ¿Qué pasa cuando haces:

for (var i = 0; i < locations.length; i++) 
{ 
    var flag = new google.maps.MarkerImage('markers/' + (i + 1) + '.png', 
     new google.maps.Size(17, 19), 
     new google.maps.Point(0,0), 
     new google.maps.Point(0, 19)); 
    var place = locations[i]; 
    var myLatLng = new google.maps.LatLng(place[1], place[2]); 
    var marker = new google.maps.Marker({ 
     position: myLatLng, 
     map: map, 
     icon: flag, 
     shape: shape, 
     title: place[0], 
     zIndex: place[3], 
     url: "/your/url/" 
    }); 

    google.maps.event.addListener(marker, 'click', function() { 
     window.location.href = this.url; 
    }); 
} 
+0

Gracias por su respuesta. Intenté esto antes y hoy una vez más. De esta forma, cada marcador tiene la misma url. Pero esto no es exactamente lo que necesito. Necesito diferentes URL. ¿Cómo establecer url1 en marker1 y url2 en marker2? – idobr

+0

El problema fue resuelto por consejo de Scessor. – idobr

-1

las respuestas anteriores no funcionaron bien para mí. Tuve problemas persistentes al establecer el marcador. Así que cambié el código un poco.

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=ANSI" /> 
    <title>Google Maps Multiple Markers</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
     type="text/javascript"></script> 
    </head> 
    <body> 
    <div id="map" style="width: 1500px; height: 1000px;"></div> 

    <script type="text/javascript"> 
     var locations = [ 
     ['Goettingen', 51.54128040000001, 9.915803500000038, 'http://www.google.de'], 
     ['Kassel', 51.31271139999999, 9.479746100000057,0, 'http://www.stackoverflow.com'], 
     ['Witzenhausen', 51.33996819999999, 9.855564299999969,0, 'www.http://developer.mozilla.org.de'] 

]; 

var map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 10, 
center: new google.maps.LatLng(51.54376, 9.910419999999931), 
mapTypeId: google.maps.MapTypeId.ROADMAP 
}); 

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

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, 
    url: locations[i][4] 
    }); 

google.maps.event.addListener(marker, 'mouseover', (function(marker, i) { 
    return function() { 
    infowindow.setContent(locations[i][0]); 
    infowindow.open(map, marker); 
    } 
})(marker, i)); 

     google.maps.event.addListener(marker, 'click', (function(marker, i) { 
    return function() { 
    infowindow.setContent(locations[i][0]); 
    infowindow.open(map, marker); 
    window.location.href = this.url; 
    } 
})(marker, i)); 

    } 

    </script> 
    </body> 
    </html> 

De esta manera funcionó para mí! Puede crear enlaces de enrutamiento de Google Maps desde su Datebase para usarlo como un mapa de enrutamiento interactivo.

Cuestiones relacionadas