Reputation: 435
I use data from Postgis, that is loaded via geojson and added as data layer on Google Maps.
//Load mapdata via geoJson
var parzelle = new google.maps.Data();
parzelle.loadGeoJson("./mapdata/get_ugs_geojson.php");
// Set the stroke width, and fill color for each polygon
var featureStyle = {
fillColor: '#ADFF2F',
fillOpacity: 0.1,
strokeColor: '#ADFF2F',
strokeWeight: 1
}
// Apply style settings to data layer
parzelle.setStyle(featureStyle);
// Add data layer to map
parzelle.setMap(map);
I would like to style the displayed polygons depending on their attributes (in this case a habitat-code). I've tried the following, but the polygons are no longer displayed.
//Load mapdata via geoJson
var parzelle = new google.maps.Data();
parzelle.loadGeoJson("./mapdata/get_ugs_geojson.php");
// Styles depending on habitat
var styles = {
6510: {fillColor: "#00cc00", fillOpacity: 0.1, strokeWeight: 1.5, strokeColor: "#00cc00", strokeOpacity: 0.8},
6430: {fillColor: "#00cc00", fillOpacity: 0.1, strokeWeight: 1.5, strokeColor: "#00cc00", strokeOpacity: 0.8},
6210: {fillColor: "#ff9900", fillOpacity: 0.1, strokeWeight: 1.5, strokeColor: "#ff9900", strokeOpacity: 0.8},
9150: {fillColor: "#993300", fillOpacity: 0.1, strokeWeight: 1.5, strokeColor: "#993300", strokeOpacity: 0.8},
9180: {fillColor: "#992200", fillOpacity: 0.1, strokeWeight: 1.5, strokeColor: "#992200", strokeOpacity: 0.8}
};
var habitat = parzelle.feature.getProperty ('fk_habitat_target');
var featureStyle = styles[habitat] || {};
parzelle.setStyle(featureStyle);
parzelle.setMap(map);
What's wrong with my code? or Maybe there is even a simpler way to style the polygons depending on their attributes?
Upvotes: 1
Views: 920
Reputation: 10879
The way that dynamic styling of data layer features works is the following, and it's actually pretty cool: Instead of providing an object containing the styling to the setStyle()
method, you provide a function that returns such an object. Inside that function, you can then react to the properties or anything else you like, in order to change the styling.
var featureStyling = function(feature) {
var StyleOptions = {
fillColor: feature.getProperty('fk_habitat_target') == 6510
? '#00cc00'
: '#993300'
};
return StyleOptions;
};
map.data.setStyle(featureStyling);
Of course, this is just a simplified example, you would probably use a switch/case statement to switch through the property and return a completely different StyleOptions object for each property value.
Upvotes: 1