2015-04-03 110 views
0

我試圖讓兩組多邊形表現爲不同的圖層,允許獨立切換圖層的可見性。例如,當添加geojson中沒有'rgb'屬性的多邊形時,我想不必爲已繪製的多邊形重新定義樣式。如何更改Google地圖中的某些多邊形樣式

我試圖不指定任何返回值的多邊形,我不想改變,但它離開了多邊形與默認的谷歌地圖樣式,儘管他們的初始風格。

var mapFrame = frames.getAtcMap(index); 
// load the geojson 
var file = "Council_Districts_2016.geojson"; 
$.get(file, function(data){ 
    var geojson = GetParsedForGoogleMaps(data); 
    mapFrame.googleMap.data.addGeoJson(geojson); 
    mapFrame.googleMap.data.setStyle(function(feature) { 
     if(typeof feature.getProperty('rgb')==="undefined"){ 
      return { 
       fillColor: "white", 
     fillOpacity:0, 
     strokeColor:"blue", 
     strokeOpacity: 0.8, 
     strokeWeight: 2.5, 
     zIndex:11 
      }; 
     }; 
    }); 
}); 

我明白setStyle重新定義了整個地圖的風格,但他們是無論如何重新定義樣式只有一套多邊形的?

+0

@duncan我發佈了更多的代碼,但我不確定如何在'Polygon.setOptions'中定義「Polygon」。將非常感謝一個片段顯示如何使用geojson導入的東西setOptions – cmbarbu 2015-04-03 11:58:07

+0

是的,我在錯誤的軌道上,我刪除了我以前的評論。您的代碼看起來與https://developers.google.com/maps/documentation/javascript/datalayer上的示例類似。 – duncan 2015-04-03 12:07:31

回答

2

谷歌搜索我發現主要有兩種可能性。

使用不同的層

更一般的和永久的解決方案。它只是爲第二組多邊形定義了一個新的獨立層。它是如何定義一個谷歌地圖上的多個層的好例子:

// global name of the layer to allow later reference 
var layerCouncilDistricts = {}; 
function addOnTopCouncilDistricts(elem){ 
    // identification of the map in my multiple maps environment 
    var index = elem.id.replace("addCouncilDistrict",""); 
    var mapFrame = frames.getAtcMap(index); 
    // construct the new layer 
    layerCouncilDistricts = new google.maps.Data(mapFrame); 
    // attach it to a google map 
    layerCouncilDistricts.setMap(mapFrame.googleMap); 
    // load the geojson 
    var file = "Council_Districts_2016.geojson"; 
    $.get(file, function(data){ 
     // parse the geojson 
     var geojson = GetParsedForGoogleMaps(data); 
     // add the geojson to the layer 
     layerCouncilDistricts.addGeoJson(geojson); 
     // set the style of the layer 
     layerCouncilDistricts.setStyle(function(feature){ 
       return { 
        fillColor: "white", 
      fillOpacity:0, 
      strokeColor:"blue", 
      strokeOpacity: 0.8, 
      strokeWeight: 2.5, 
      zIndex:11 
     }}); 
    }); 
} 

對於臨時變化

第二種方法是精細的臨時變化,但該組的從別人特徵不分離。可以使用foreach() of the data class查看所有功能並覆蓋樣式。在我的例子中是這樣的:

// examine each feature 
mapFrame.googleMap.data.forEach(function(feature) { 
    // is feature to be changed 
    if(typeof feature.getProperty('rgb')==="undefined") { 
    // override existing style for this feature 
    overrideStyle(feature,{ 
     fillColor: "white", 
     fillOpacity:0, 
     strokeColor:"blue", 
     strokeOpacity: 0.8, 
     strokeWeight: 2.5, 
     zIndex:11 
    }); 
    } 
} 

它很好用,並且允許進一步與圖層進行完全獨立於其他項目的交互。