2012-10-05 48 views
1

我一直在試圖在谷歌地圖上創建一些多邊形疊加層,點擊時它會鏈接到另一個新窗口中的網頁。但它只能鏈接到最後生成的多邊形的URL。任何想法爲什麼?我想我錯過了一些基本的東西,但它是如何生成多邊形,然後嘗試從它們拉出URL?谷歌地圖事件點擊收聽者

<script type="text/javascript"> 
    var mapSquares = {}; 

    mapSquares['square1'] = { 
    coords: [ 
     new google.maps.LatLng(52.572177, -0.247192), 
     new google.maps.LatLng(52.612177, -0.247192), 
     new google.maps.LatLng(52.612177, -0.347192), 
     new google.maps.LatLng(52.572177, -0.347192) 
      ], 
    url: 'http://www.google.co.uk' 
    }; 

    mapSquares['square2'] = { 
    coords: [ 
     new google.maps.LatLng(52.522177, -0.247192), 
     new google.maps.LatLng(52.572177, -0.247192), 
     new google.maps.LatLng(52.572177, -0.347192), 
     new google.maps.LatLng(52.522177, -0.347192) 
      ], 
    url: 'http://www.bbc.co.uk' 
    } 

var allMapSquares; 

function initialize() { 
    var myLatLng = new google.maps.LatLng(52.572177, -0.247192); 
    var mapOptions = { 
    zoom: 12, 
    center: myLatLng, 
    mapTypeId: google.maps.MapTypeId.TERRAIN 
    }; 

var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions); 

    for (var mapSquare in mapSquares) { 
    var drawMapSquare = { 
     paths: mapSquares[mapSquare].coords, 
     strokeColor: "#FF0000", 
     strokeOpacity: 0.8, 
     strokeWeight: 3, 
     fillColor: "#FF0000", 
     fillOpacity: 0.35, 
     map: map 
    }; 

    google.maps.event.addListener(drawMapSquare, 'click', function() { 
     window.open(mapSquares[mapSquare].url,'_blank'); 
    }); 

    allMapSquares = new google.maps.Polygon(drawMapSquare); 

    } 

} 
</script> 

非常感謝!

回答

1

當你放在for循環中並傳遞mapSquare作爲mapSquares []數組變量的索引時,它會取最後一個值,因爲循環迭代到,mapSquare的最後一個位置是最後一個位置,所以它會根據您的for環這就是爲什麼你總是讓最後一個環節

google.maps.event.addListener(drawMapSquare, 'click', function() { 
    window.open(mapSquares[mapSquare].url,'_blank'); // here this will call when you click and at that time mapSqare position was last. 
}); 
+0

好的。我現在看到了。那麼解決這個問題最好的辦法是什麼? – user1722729

0

我也遇到這個問題,最簡單的方法是:將實際創建信息窗口,並添加事件監聽到一個單獨的函數調用的代碼塊。這實際上可以避免全局和局部變量問題。

原因在Pratik的答案中解釋。

相關問題