Geojson map with D3 only rendering a single path in a feature collection

Problem

All your features are drawing, you are correctly using your path and enter cycle. To see, set your fill to none:

enter image description here

You can see them when inspecting the svg: all the paths are there.

Why don’t you see them in the map when they have fill? Because the the polygons are inverted, they cover the entire world except for the region of interest. While most other geographic libraries/renderers treat geojson as Cartesian, D3 does not. This means winding order matters. Your coordinates are wound in the wrong order.

Solution

To properly fill, draw all features, and support mouse interaction, you’ll need to reverse the winding order of the polygons. You can do this on the fly, or create new geojson files to store the pre-reversed data.

To do so let’s take a look at your data. You are working with only features that are MultiPolygons, let’s look at the structure:

{ 
  type:"Feature",
  properties: {...},
  geometry: {
    type: "MultiPolygon",
    coordinate: /* coordinates here */
  }
}

Coordinates are structured as so:

 coordinates:[polygons] // an array of polygons

The individual polygons are structured as so:

 [outer ring][inner ring][inner ring]... // an array of coordinates for an outer ring, an array of coordinates for each hole (inner ring).

Polygon rings are structured as an array of long lats, with the first and last values being the same.

[x,y],[x,y]....

So, to reverse the ordering of the coordinates, we need to reverse the items in the ring arrays:

 features.forEach(function(feature) {
   if(feature.geometry.type == "MultiPolygon") {
     feature.geometry.coordinates.forEach(function(polygon) {
       polygon.forEach(function(ring) {
         ring.reverse(); 
       })
     })
   }
 })

If we had polygons in the mix too (they are slightly less nested), we could use:

 features.forEach(function(feature) {
   if(feature.geometry.type == "MultiPolygon") {
     feature.geometry.coordinates.forEach(function(polygon) {

       polygon.forEach(function(ring) {
         ring.reverse();
       })
     })
   }
   else if (feature.geometry.type == "Polygon") {
     feature.geometry.coordinates.forEach(function(ring) {
       ring.reverse();
     })  
   }
 })

Here’s an updated plunker

Leave a Comment