For Google Maps API v3...
I'm trying to let two sets of polygons behave as different layers, allowing to toggle the visibility of the layers independently. For example, when adding polygons from a geojson where their is no 'rgb' property I would like not to have to redefine the style for already drawn polygons.
I tried to not specify any return value for the polygons I don't want to change but it leaves the polygons with the default of google maps style in spite of their initial style.
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
};
};
});
});
I understand setStyle
redefines the style of the whole map but is their anyway to redefine the style only of a set of the polygons?
Googling around I've found mainly two possibilities.
The more general and permanent solution. It simply defines a new independent layer for this second set of polygons. It is a good example on how to define multiple layers on a google map:
// 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
}});
});
}
The second method is fine for temporary changes but does not separate this set of features from the others. One can use foreach()
of the data class to review all features and override the style. In my example something like:
// 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
});
}
}
It works great and allows to further interact with the layer completely independently of other items.