谷歌地图标记作为链接

时间:2010-06-16 18:43:30

标签: javascript google-maps

我在网站上使用谷歌地图,我想如何使用标记作为链接?我的意思是当我点击标记打开特定链接时。

提前谢谢!

2 个答案:

答案 0 :(得分:11)

这实际上非常容易。只需将事件处理程序附加到标记,然后通过将window.location.href设置为您的URL来启动链接。看看下面的例子,我认为这些例子应该是自我解释的:

使用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>

使用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>

以上示例将在大西洋的某处添加标记。当您点击它时,您将被转发到热门的搜索引擎。

答案 1 :(得分:2)

要在新标签页中打开它,请在“window.location.href = marker.url;”之后添加以下内容:

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

所以你会:

google.maps.event.addListener(marker, 'click', function() {
      window.location.href = marker.url;
      window.open(this.url, '_blank');
    });
相关问题