簡體   English   中英

在Google地圖中單擊多邊形內部

[英]Clicking inside a polygon in Google Maps

包含的JavaScript代碼段應該執行以下操作:

  1. 當用戶點擊地圖時,初始化headMarker並在其周圍繪制一個圓(多邊形)

  2. 當用戶在圓圈內單擊時,初始化tailMarker並繪制這兩個標記之間的路徑

1正如預期的那樣發生。 但是當用戶在圓圈內部點擊時,在function(overlay,point)overlay非空,而point為null。 因此,代碼無法初始化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}); 
    }
});

您需要做的就是在圓圈的GPolygon構造函數中設置clickable: false選項。 以下是我用來回答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地圖在多邊形內部單擊

我使用鑽石代替圓圈,因為它們更容易在v2 API中繪制。 請注意,如果未使用clickable: false選項創建多邊形,則click偵聽器的latlng參數將為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM