13

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
map.data.loadGeoJson(
        'https://storage.googleapis.com/mapsdevsite/json/google.json');

//2nd json file  (same as #1 for illustration purpose)
map.data.loadGeoJson(
        'https://storage.googleapis.com/mapsdevsite/json/google.json');

    // I want to style each Json file independently
    map.data.setStyle({
        fillColor: 'green',
        strokeWeight: 1
    });

   // map1.setMap(map);


}

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

  data_layer.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');


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

    nLayer.setMap(map);

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

user2668812
  • 417
  • 6
  • 16
  • Here's an example where they style each letter's colour based on a property in the JSON file: https://developers.google.com/maps/documentation/javascript/examples/layer-data-event – duncan Aug 23 '16 at 16:35
  • I am looking for an example that uses a static Json file. – user2668812 Aug 23 '16 at 16:56
  • That's exactly what that example's doing: https://storage.googleapis.com/maps-devrel/google.json – duncan Aug 23 '16 at 17:10
  • Duncan - the Json fines that I have are static and cant be modified, this is why I need to style them independently.. Perhaps I.m missing a way to change the json file once loaded with JavaScript. – user2668812 Aug 23 '16 at 17:23

3 Answers3

17

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
});
Community
  • 1
  • 1
Matej P.
  • 5,303
  • 1
  • 28
  • 44
  • The second option looks like it may work, do you have an example of how to add these 2 layers to the map ? – user2668812 Aug 23 '16 at 18:39
  • I have added code sample, or what do you mean? just create the data layer using `var data_layer = new google.maps.Data({map: map});` and it will be added to the map. – Matej P. Aug 23 '16 at 19:14
  • this works on one layer. I'll try it on the others. Thanks for the help. – user2668812 Aug 23 '16 at 19:29
  • many thanks @MatejP. I was also looking for exact this 'another option', which should be in the example described I think. only thing im not sure how to figure out: is there a way to set specific general styles on all layers or am I now forced to break the DRY principle? ;) – Christoph Lösch Jan 02 '20 at 02:30
0

I think you'll want to add the polygons and their style individually. From the example ( https://developers.google.com/maps/documentation/javascript/examples/polygon-arrays )

// Define the LatLng coordinates for the polygon.
var triangleCoords = [
    {lat: 25.774, lng: -80.190},
    {lat: 18.466, lng: -66.118},
    {lat: 32.321, lng: -64.757}
];

// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
  paths: triangleCoords,
  strokeColor: '#FF0000',
  strokeOpacity: 0.8,
  strokeWeight: 3,
  fillColor: '#FF0000',
  fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
RickTakes
  • 1,197
  • 1
  • 9
  • 14
0

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

Nate Beers
  • 1,355
  • 2
  • 13
  • 22