2010-06-16 91 views

回答

10

這實際上很容易做到。只需將事件處理程序附加到您的標記,然後通過將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?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> 

以上的例子將添加標記的地方:

<!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大西洋。當你點擊它時,你會被轉發到一個流行的搜索引擎。

+0

謝謝老兄! – 2010-06-17 07:41:56

+0

嘿+1已添加,但如果你想在新窗口中打開此鏈接,我試過window.open = marker.url;然後像 這樣的屬性url:「http://www.google.com」, target:「_blank」到標記對象但無濟於事, – defau1t 2011-12-18 20:24:00

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