style multiple GeoJson files with the Google Maps Javascript API v3 data layer
I have created a demo on github where I load polygons (boundaries) using Data Layer
and I also show how to keep reference to respective polygons and update their specific styles. Check out this SO answer for a snippet (I don't want to copy it here, because it's redundant).
Notice mainly: new_boundary.feature = data_layer.getFeatureById(boundary_id);
where I store reference to specific feature, which styles I can update anytime using e.g.:
data_layer.overrideStyle(new_boundary.feature, {
fillColor: '#0000FF',
fillOpacity: 0.9
});
And it would just update that one polygon, not all of them. So if your polygons in geoJSON files have some unique ids, or you can assign ids to all of them, you can then reference and change their styles based on that.
Another option, not shown in the example is, to have multiple data layers. It's possible to have multiple data layers in your application, e.g. create them like this:
var data_layer = new google.maps.Data({map: map});
var data_layer_2 = new google.maps.Data({map: map});
and then load data to them and change styles:
data_layer.loadGeoJson(
'https://storage.googleapis.com/mapsdevsite/json/google.json');
data_layer_2.loadGeoJson(
'https://storage.googleapis.com/mapsdevsite/json/google.json');
data_layer.setStyle({
fillColor: 'green',
strokeWeight: 1
});
data_layer_2.setStyle({
fillColor: 'blue',
strokeWeight: 2
});
I think the best way to do this is to add a property to your feature, inside the json file you load, like so:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"county": "hernando"
},
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-82.7784371,
28.694206
],
[
-82.778214,
28.6939659
],
]
]
]
}
}
]
}
Note the important part:
"properties": {
"county": "hernando"
},
Each one of your json files can have as many properties
as you want
Then in your javascript file, you can do something like this:
var map = new google.maps.Map($el[0], args);
map.data.loadGeoJson(
'/wp-content/themes/hello-theme-child-master/county-json/pinellas.json'
);
map.data.loadGeoJson(
'/wp-content/themes/hello-theme-child-master/county-json/pasco.json'
);
map.data.loadGeoJson(
'/wp-content/themes/hello-theme-child-master/county-json/hillsborough.json'
);
map.data.setStyle( function ( feature ) {
var county = feature.getProperty('county');
var color = '';
if ( county === 'pasco ) {
color = 'orange'
}
else {
color = 'green'
}
return {
fillColor: color,
strokeWeight: 1
};
});
The important part to note there is that you must pass a function to setStyle
, so that it automatically iterates through every feature