2010-05-19 244 views
4

包含的JavaScript代碼段應該做到以下幾點:點擊谷歌地圖多邊形內

  1. 在地圖上的用戶點擊,初始化headMarker和周圍畫

  2. 圓(多邊形)
  3. 作爲圈內用戶點擊,初始化tailMarker並畫出這兩個標記作爲預期

1正在發生之間的路徑。但是當用戶點擊圈內時,在function(overlay,point),overlay中非空,而point爲空。因此,代碼無法初始化tailMarker。

有人可以告訴我一個出路。

GEvent.addListener(map, "click", function(overlay,point) { 
    if (isCreateHeadPoint) { 
     // add the head marker 
     headMarker = new GMarker(point,{icon:redIcon,title:'0'}); 
     map.addOverlay(headMarker); 
     isCreateHeadPoint = false; 
     // draw the circle 
     drawMapCircle(point.lat(),point.lng(),1,'#cc0000',2,0.8,'#0',0.1); 
    } else { 
     // add the tail marker 
     tailMarker = new GMarker(point,{icon:greenIcon,title:''}); 
     map.addOverlay(tailMarker); 
     isCreateHeadPoint = true; 
     // load thes path from head to tail 
     direction.load("from:" + headMarker.getPoint().lat()+ ", " + 
         headMarker.getPoint().lng()+ " " + 
         "to:" + tailMarker.getPoint().lat() + "," + 
         tailMarker.getPoint().lng(), 
         {getPolyline:true}); 
    } 
}); 

回答

1

所有你需要做的是設置在GPolygon構造的圓的clickable: false選項。下面是我用來回答another similar question on Stack Overflow一個例子:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps Clicking Inside a Polygon</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: 450px; height: 300px"></div> 

    <script type="text/javascript"> 
     var map = new GMap2(document.getElementById("map")); 
     map.setCenter(new GLatLng(37.4419, -122.1419), 13); 

     GEvent.addListener(map, "click", function(overlay, latlng) { 
     var lat = latlng.lat(); 
     var lon = latlng.lng(); 
     var latOffset = 0.01; 
     var lonOffset = 0.01; 
     var polygon = new GPolygon([ 
      new GLatLng(lat, lon - lonOffset), 
      new GLatLng(lat + latOffset, lon), 
      new GLatLng(lat, lon + lonOffset), 
      new GLatLng(lat - latOffset, lon), 
      new GLatLng(lat, lon - lonOffset) 
     ], "#f33f00", 5, 1, "#ff0000", 0.2, { clickable: false }); 

     map.addOverlay(polygon); 
     }); 
    </script> 
</body> 
</html> 

上面的例子中的截圖:

Google Maps Clicking Inside a Polygon

我用鑽石,不是圓的,因爲它們更容易在V2畫API。請注意,如果未使用clickable: false選項創建多邊形,則click偵聽器的參數latlng應爲空。

+0

非常感謝。有用。它奇怪,你必須設置clickable:「false」爲啓用點擊(我以爲它會是可點擊的:true) – user315067 2010-05-22 01:18:39

+0

@ amarsh-anand:是的,基本上通過設置它'可點擊:假'你告訴API發生在多邊形上的點擊應該作爲點擊來處理,而不是點擊多邊形。 – 2010-05-22 01:35:41