Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps marker as a link

I am using Google Maps for my website and I wander how can I use the Markers as links? I mean when I click a marker to open a particular link.

Thank you in advance!

like image 579
Dimitar Vouldjeff Avatar asked Jun 16 '10 18:06

Dimitar Vouldjeff


2 Answers

That's actually very easy to do. Simply attach an event handler to your marker, and then launch the link by setting window.location.href to your URL. Check out the following examples, which I think should be self explanatory:

Using the v3 API:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Marker as a Link</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: new google.maps.LatLng(35.55, -25.75),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      url: 'http://www.google.com/',
      map: map
    });

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

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

Using the V2 API:

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps Marker as a Link</title> 
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false"
            type="text/javascript"></script> 
  </head> 
  <body onunload="GUnload()"> 
    <div id="map" style="width: 500px; height: 400px;"></div> 

    <script type="text/javascript"> 
      var map = new GMap2(document.getElementById("map"));
      var centerPoint = new GLatLng(35.55, -25.75);
      map.setCenter(centerPoint, 2);

      var marker = new GMarker(map.getCenter());
      marker.url = 'http://www.google.com/';
      map.addOverlay(marker);

      GEvent.addListener(marker, 'click', function() {     
        window.location.href = marker.url;
      });
    </script> 
  </body> 
</html>

The above examples will add a marker somewhere in the atlantic ocean. When you click on it, you'll be forwarded to a popular search engine.

like image 171
Daniel Vassallo Avatar answered Sep 30 '22 19:09

Daniel Vassallo


To get this to open in a new tab add the following right after the "window.location.href = marker.url;":

window.open(this.url, '_blank');

So you would have:

google.maps.event.addListener(marker, 'click', function() {
      window.location.href = marker.url;
      window.open(this.url, '_blank');
    });
like image 22
moorewebx Avatar answered Sep 30 '22 21:09

moorewebx