55

I want to open a new window by clicking on a marker using Google Maps API 3.

Unfortunately there are not many examples for the Google Maps API and I found out this code:

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

How to use it, when I create markers with a loop? I tried it in many ways with no afford.

This is my code – I made it simple and short:

<!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>

How to open url by clicking on marker with code above?

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
idobr
  • 1,537
  • 4
  • 15
  • 31

6 Answers6

113

You can add a specific url to each point, e.g.:

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']
];

Add the url to the marker values in the for-loop:

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

Then you can add just before to the end of your for-loop:

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

Also see this example.

scessor
  • 15,995
  • 4
  • 43
  • 54
  • Thanks for reply. In this way the last url opens for each marker. I tried this and didn't find the way to fix it. I checked your example (link above): as far as I can judge: there is the same problem - when you click at marker there is "stackoverflow link" for each marker. – idobr Jan 07 '12 at 21:16
  • That is really great! It works. I thought the problem was with a wrong place for listener. Thank you very much. – idobr Jan 07 '12 at 22:22
  • You're welcome. If you are satisfied with the answer, please mark it as the correct answer. – scessor Jan 07 '12 at 22:30
  • Done. (I was just reading faq to find out how to mark the right answer.) Thanks. – idobr Jan 07 '12 at 22:37
  • I've noticed a problem after adding new code: there are no marker's names tips, when mouse is over marker. Before changes were done: there were marker's names "onmouseover": "name1", "name2". (Example (link above) has this problem too.) – idobr Jan 08 '12 at 10:23
  • I have tooltips ('name1', ...) over the markers on hover in FF9, IE8 and Chrome in [my example above](http://fiddle.jshell.net/bTujZ/). – scessor Jan 08 '12 at 11:23
  • There are probably no tooltips in Opera 11.60 (opera.com). (I have only a bit buggy netbook with Opera at present). I have tooltips in IE8. If it works in main browsers, then it's good. Thank you for quick and informative answers. – idobr Jan 08 '12 at 12:07
  • Google maps doesn't support opera (see this [link](http://support.google.com/maps/bin/answer.py?hl=en&answer=16532)). Hover of titles in opera is a known issue. – scessor Jan 08 '12 at 12:28
  • I was using `marker.url`and it was redirecting to the last url, but when I used `this.url` it worked thanks – Durgesh Kumar Jan 19 '18 at 15:12
  • @scessor the [link](http://fiddle.jshell.net/bTujZ/) is broken and not working. Could you fix this? – cse Oct 26 '18 at 11:14
6

url isn't an object on the Marker class. But there's nothing stopping you adding that as a property to that class. I'm guessing whatever example you were looking at did that too. Do you want a different URL for each marker? What happens when you do:

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;
    });
}
duncan
  • 31,401
  • 13
  • 78
  • 99
  • Thank you for reply. I tried this before and today once more. In this way every marker has the same url. But this is not exactly what I need. I need different urls. How to set url1 to marker1 and url2 to marker2? – idobr Jan 07 '12 at 21:05
  • How was it solved? I have a similar project, where each marker click has to open a function in a div. – DanielaB67 May 20 '18 at 14:52
1
google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    window.location.href = marker.url;
  }
})(marker, i));
  • 2
    Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 21 '20 at 00:36
0

If anyone wants to add an URL on a single marker which not require for loops, here is how it goes:

if ($('#googleMap').length) {
    var initialize = function() {
        var mapOptions = {
            zoom: 15,
            scrollwheel: false,
            center: new google.maps.LatLng(45.725788, -73.5120818),
            styles: [{
                stylers: [{
                    saturation: -100
                }]
            }]
        };
        var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: map.getCenter(),
            animation: google.maps.Animation.BOUNCE,
            icon: 'example-marker.png',
            map: map,
            url: 'https://example.com'
        });

        //Add an url to the marker
    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
    }
    // Add the map initialize function to the window load function
    google.maps.event.addDomListener(window, "load", initialize);
}
Louis Chaussé
  • 167
  • 4
  • 11
0
    function loadMarkers(){
          {% for location in object_list %}
              var point = new google.maps.LatLng({{location.latitude}},{{location.longitude}});
              var marker = new google.maps.Marker({
              position: point,
              map: map,
              url: {{location.id}},
          });

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

          {% endfor %}
Stackaccount1
  • 139
  • 1
  • 12
-1

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!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>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.