2012-03-04 66 views
3

我有一個使用Google地圖JavaScript API V3的網站。 我想通過在地圖頂部放置一個半透明的顏色來突出顯示感興趣的區域,並在中間切一個孔。見附圖。將掩碼應用於Google地圖

切口的位置可以在任何地方。我能夠計算切出的像素(或緯度/經度)座標,但我正在努力的是如何最好地創建一個蒙版。我看了一下Google的圖片拼貼和多邊形,但看不到一個簡單的方法來實現這一點。任何人都可以提供任何關於繼續進行的最佳方式的指針嗎?

mask with cut-out

回答

3

想通了。櫃面任何人都需要做到這一點...

function MaskClass(map){ 

    //constants 
    var MAP_MAX_LAT = 85; 
    var MAP_MIN_LAT = -85; 
    var MAP_MAX_LNG = 179; 
    var MAP_MIN_LNG = -179; 

    // Object initialisation - create 4 rectangles to mask off the area 
    var rectangleInitialisationOptions = { 
     map: map, 
     fillColor: "#F00", 
     fillOpacity: 0.3, 
     strokeOpacity: 0, 
     clickable: false 
     }; 

    this.rectangle1 = new google.maps.Rectangle(rectangleInitialisationOptions); 
    this.rectangle2 = new google.maps.Rectangle(rectangleInitialisationOptions); 
    this.rectangle3 = new google.maps.Rectangle(rectangleInitialisationOptions); 
    this.rectangle4 = new google.maps.Rectangle(rectangleInitialisationOptions); 

    // Method to place the cut-out 
    this.setMask = function(boundsSouthWest, boundsNorthEast){ 

     var swLat = boundsSouthWest.lat(); 
     var swLng = boundsSouthWest.lng(); 
     var neLat = boundsNorthEast.lat(); 
     var neLng = boundsNorthEast.lng(); 

     this.rectangle1.setBounds(
      new google.maps.LatLngBounds(
       new google.maps.LatLng(neLat, MAP_MIN_LNG), 
       new google.maps.LatLng(MAP_MAX_LAT, MAP_MAX_LNG))); 

     this.rectangle2.setBounds(
      new google.maps.LatLngBounds(
       new google.maps.LatLng(MAP_MIN_LAT, MAP_MIN_LNG), 
       new google.maps.LatLng(swLat, MAP_MAX_LNG))); 

     this.rectangle3.setBounds(
      new google.maps.LatLngBounds(
       new google.maps.LatLng(swLat, MAP_MIN_LNG), 
       new google.maps.LatLng(neLat, swLng))); 

     this.rectangle4.setBounds(
      new google.maps.LatLngBounds(
       new google.maps.LatLng(swLat, neLng), 
       new google.maps.LatLng(neLat, MAP_MAX_LNG))); 

     this.setVisible(true); 
    }; 

    // Method to show/hide the mask 
    this.setVisible = function(visibility){ 
     this.rectangle1.setVisible(visibility); 
     this.rectangle2.setVisible(visibility); 
     this.rectangle3.setVisible(visibility); 
     this.rectangle4.setVisible(visibility); 
    }; 

} 

使用它...

theMask = new MaskClass(referenceToYourMap); //create mask 

theMask.setMask(boundsSouthWest, boundsNorthEast); //place mask somewhere 

theMask.setVisible(false); //hide mask 
+0

感謝分享 – 2012-03-04 22:59:37

+1

一個的jsfiddle的任何機會展示這方面的工作? – blarg 2013-03-07 10:04:11

+0

我知道這是遲到,但我沒有問題的工作。我試圖讓面具可以拖動,這將是有趣的:) – 2015-09-03 19:46:30