user2668812 user2668812 - 1 year ago 303
Javascript Question

style multiple GeoJson files with the Google Maps Javascript API v3 data layer

I have a site that uses google api v3 for showing polygons from json files.

the site has multiple json polygons, I need to style each polygon with a different color and create a handle to the shape.

The only examples that I can find refer to pure polygons and not json files, there is one example that changes the json file (i cant do this as the json files are static.

sample code:

var map;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: { lat: 45, lng: -90 }

//1st Json file

//2nd json file (same as #1 for illustration purpose)

// I want to style each Json file independently{
fillColor: 'green',
strokeWeight: 1

// map1.setMap(map);


I managed to get the layer added to the map using,


// Construct the polygon.
var nLayer = new google.maps.JSON({
paths: data_layer,
strokeColor: 'green',
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: 'green',
fillOpacity: 0.8


I cannot get the style to apply to the map. any ideas ?

Answer Source

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:

    fillColor: 'green',
    strokeWeight: 1
    fillColor: 'blue',
    strokeWeight: 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download