[javascript] Google Maps API: open url by clicking on marker

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?

The answer is


    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 %}

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

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.


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);
}

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;
    });
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to google-maps-api-3

Google Maps shows "For development purposes only" Googlemaps API Key for Localhost ERROR: Google Maps API error: MissingKeyMapError Google Maps API warning: NoApiKeys Google Maps JavaScript API RefererNotAllowedMapError This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console TypeError: window.initMap is not a function Google maps Marker Label with multiple characters Google Maps how to Show city or an Area outline How to use SVG markers in Google Maps API v3

Examples related to google-maps-markers

How to change icon on Google map marker Auto-center map with multiple markers in Google Maps API v3 Resize Google Maps marker icon image How to create a custom-shaped bitmap marker with Android map API v2 Draw path between two points using Google Maps Android API v2 Google Maps API Multiple Markers with Infowindows Javascript, Change google map marker color How do you create a Marker with a custom icon for google maps API v3? Selecting last element in JavaScript array google maps v3 marker info window on mouseover