Drawing individual polygons - buildings, country borders, etc on a map (looping through index buffer) in WebGL

1k views Asked by At

I am using WebGL to draw lines and polygons on a canvas layer on top of my map for OSM data. I have written a query that returns a list of polygons from the planet_osm_polygon table. It returns the list as JSON objects. I am using

 gl.drawElements(gl.LINES, vetexIndex.length, gl.UNSIGNED_SHORT, 0) 

To draw the polygons.

My index buffer looks like this:

pIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, pIndexBuffer); 
pVertexIndices = new Uint16Array([0,1, 1,2, 2,3]);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, pVertexIndices, gl.STATIC_DRAW);

Here, for the indices of the polygon, I have used 0,1 1,2 and 2,3 as pairs, which draws a three consecutive lines (as border surrounding the polygon) I would want to draw several other polygons like this. Without the use of drawElements() and index buffers, using just drawArrays() and gl.LINE_STRIP as so:

gl.drawArrays(gl.LINESTRIP, 0, json_data_length)

Draws the polygons but connects one end of each polygon with the next one (since it is a LINE_STRIP).

How can I draw separate individual polygons on my map? How can I use my index buffer here, for each polygon?

I do not want to use any external library; just plain JavaScript. I have already converted the lat-long coordinates from my OSM database into pixel coordinates in my JavaScript code.

using gl.LINE_STRIP

enter image description here

using gl.LINES and an index buffer

enter image description here

1

There are 1 answers

6
aeskreis On BEST ANSWER

The only way you will be able to draw multiple polylines in a single draw call is to use GL_LINES. When OpenGL goes to render a buffer using GL_LINES or GL_LINESTRIP it will need 2 vertices from your vertex buffer, and use these 2 point to draw a line. The behavior of GL_LINES vs GL_LINESTRIP differs as follows:

GL_LINES:

line 1 - v[0], v[1]
line 2 - v[2], v[3]
line 3 - v[4], v[5]
...

GL_LINESTRIP

line 1 - v[0], v[1]
line 2 - v[1], v[2]
line 3 - v[2], v[3]
...

So as you can see, if you do not use GL_LINES, then you will not be able to disconnect the lines, and the lines will be considered one continuous polyline. The only exception is if you insert a degenerate primitive, but this is an advanced technique that I do not recommend for a beginner such as yourself.

Best of luck. Hope this solves your problem.

EDIT: My mistake, degenerate primitives only applies to GL_TRIANGLE_STRIP, it is not possible to draw degenerates with GL_LINESTRIP.