[GIS] Convert Multipolygon Geojson to multiple geojson polygons

geojsonjavascriptnode-jspolygon

I see a lot of questions going from Polygons to MultiPolygon, but is there some easy way to go the other way around? It would also be useful to preserve the attributes from the MultiPolygon to apply to the new Polygons.

Best Answer

If you have a simple Multipolygon such as the one below,

mp=
  {
  "type": "MultiPolygon",
  "coordinates": [
    [
        [
            [-99.028, 46.985], [-99.028, 50.979],
            [-82.062, 50.979], [-82.062, 47.002],
            [-99.028, 46.985]
        ]
    ],
    [
        [
            [-109.028, 36.985], [-109.028, 40.979],
            [-102.062, 40.979], [-102.062, 37.002],
            [-109.028, 36.985]
        ]
     ]
  ]
}

then using Javascript/Nodejs you can access each constituent Polygon using forEach, and write out a new Polygon using JSON.stringify

mp.coordinates.forEach(function(coords){
   var feat={'type':'Polygon','coordinates':coords};
   console.log(JSON.stringify(feat));
   }
);

You could also access them directly in a loop, if you prefer a less functional way, indexed on mp.coordinates.length eg,

for (var i=0;i<mp.coordinates.length;i++){   
   var feat={'type':'Polygon','coordinates':mp.coordinates[i]};
   console.log(JSON.stringify(feat));
}

If you are dealing with a FeatureCollection, where you might have an array of feature, each containing a MultiPolygon, eg,

mp = {
  "type": "FeatureCollection",
  "features": [
     {
      "type": "Feature",
       "geometry": {
         "type": "MultiPolygon",
           "coordinates": [
             [[
              [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0],
              [100.0, 0.0]
            ]],
            [[
             [0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0],
             [0.0, 0.0]
           ]]          
         ]
     },
      "properties": {
      "prop1": {
        "this": "that"
      },
      "prop0": "value0"
     }
    }
  ]
}

Then, you can use forEach to get to each feature, and then access each Polygon within each Multipolygon simply by looping through the array, as the first dimension of the coordinates array, is the index into each Polygon. Note, you can also save the properties, and assign them to each new Polygon feature.

 mp.features.forEach(function(feat){
   var geom=feat.geometry; 
   var props=feat.properties;
   if (geom.type === 'MultiPolygon'){
      for (var i=0; i < geom.coordinates.length; i++){
          var polygon = {
               'type':'Polygon', 
               'coordinates':geom.coordinates[i],
               'properties': props};
          console.log(JSON.stringify(polygon));
      }
    }
 });

If you want something more sophisticated, you could look into modifying the OpenLayers.Format.GeoJSON class.