sprucegoose sprucegoose - 1 year ago 206
Javascript Question

How can I draw geoJSON in three.js as a mesh and not a line, and fill with color?

I'm making a globe in three.js and will be adding some data layers. All of the layers will be created from geoJSON. I have set it up so that the globe (the first data file, which is of countries) shows up as lines. This uses ThreeGeoJSON.

globe with lines

However, I do not want just outlines. I'd like to fill the countries with color.

My current project can be seen here:

The code is here:

I tried to create a new function that would render the polygons and multipolygons as meshes instead of lines. That function is as follows:

function drawShape(x_values, y_values, z_values, options) {
var shape_geom = new THREE.BoxGeometry();
createVertexForEachPoint(shape_geom, x_values, y_values, z_values);

var shape_material = new THREE.MeshBasicMaterial( {color: 0xffff00 } );
var shape = new THREE.Mesh(shape_geom, shape_material);


Unfortunately, nothing shows up when I use that. There are no errors in the console to help me understand why.

Can anyone explain how I could set up the countries so that they can be filled? Any advice or pointers would be very much appreciated.

Answer Source

You have segments which form an outline and draw them as lines. But filled shape is have to be constructed from triangles (more on webgl draw modes there).

So to render filled country you need to make a triangulation of your set of segments. There are multiple ways to do that, and ready to use code is available (for example, this earcut implementation).

However, since you want to map shape on globe, next problem could be the size of produced polygons. If triangulation you use produces big triangles, and you transform vertices to spherical coords, big triangles will be noticable flat. Here could be used displacement mapping in fragment shader or further triangles subdivision (based on triangles area, for example).

The last but not the least: triangulation is computationally expensive, so if you don't need to do it dynamically, consider offline geometry preparation. If you need to triangulate dynamic data: consider using webworker for that task (or super-fast non javascript server if project is big).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download