I’ve always been fascinated with maps, and they’re one of my favorite type of UX on the web. So when I wanted to learn a bit more about 3D programming and WebGL, it made sense to try and implement something I was already familiar with; a vector map.
This article covers my process of building a vector-tile map from the ground up. I've broken it up into three main parts:
TL;DR - You can also head straight to the source or check out the final product.
If you've ever wondered exactly how vector maps like Mapbox or Google Maps are rendered, this aticle should break down a few of the lower-level concepts for what goes on under the hood when using a vector based map. The implementation details in these examples won’t match exactly what other maps do, but the concepts should still be more-or-less the same.
I'm also still fairly new 3D programming, so feel free to shoot me a note if there are any suggestions or improvements to the code. 😅
To start, we should probably talk a bit about map projections, in particular the Mercator projection. It’s the standard projection you’ll see in almost all web-based maps. One thing to note, is the distance between latitudes becomes greater near the poles, so there’s a decent amount of distortion the further north and south points are.
The Web Mercator projection is a slight variation on Mercator, but the formulas still mostly apply. For web maps, the origin (0, 0) is considered to be at the top-left, with x+ increasing to the right, and y+ increasing downwards.
So we can use the projection formulas convert our latitude & longitude values to an XY value on the map. For these examples, I’m going to use code from the MercatorCoordinate class that is a part of the Mapbox GL JS library.
class MercatorCoordinate {
static mercatorXfromLng(lng) {
return (180 + lng) / 360;
}
static mercatorYfromLat(lat) {
return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;
}
static fromLngLat(lngLat) {
const x = MercatorCoordinate.mercatorXfromLng(lngLat[0]);
const y = MercatorCoordinate.mercatorYfromLat(lngLat[1]);
return [x, y];
}
}
So if we take an example point [-73.9911, 40.7343] (NYC), we can convert it to a point in the XY space. We'll call this coordinate system the "world space". We can think of this as a single map tile at zoom level 0.
const [x, y] = MercatorCoordinate.fromLngLat([-73.9911, 40.7343]);
x // 0.294469
y // 0.375901
Now that we have our “world space” coordinates, we can convert them to the “clip space” coordinates that WebGL uses to render a scene. The clip space is slightly different than our world space, in that the origin is at the center, and going from [-1, 1] on the axes.
So we can convert our world space -> clip space with some pretty basic math. This can also be done via a matrix transformation (which we’ll cover later), but for simplicity we can just do this conversion in our MercatorCoordinate utility.
static fromLngLat(lngLat) {
let x = MercatorCoordinate.mercatorXfromLng(lngLat[0]);
let y = MercatorCoordinate.mercatorYfromLat(lngLat[1]);
// adjust so relative to origin at center of viewport, instead of top-left
x = -1 + (x * 2);
y = 1 - (y * 2);
return [x, y];
}
Now that we have a way to convert latitude & longitude to our WebGL coordinate space, lets go ahead and draw something! We’ll start simple and draw a basic bounding box.
Since our initial view is zoomed all the way out (zoom level 0), we’ll use a box large enough to see, so we’ll bound the continental US.
const USA_BBOX = [
[-126.03515625, 23.079731762449878],
[-60.1171875, 23.079731762449878],
[-60.1171875, 50.233151832472245],
[-126.03515625, 50.233151832472245]
];
In order to render a box in WebGL, we need to convert it into a set of triangles, which is the smallest primitive type for rendering a surface. A rectangle is a pretty simple shape, which can be drawn with two triangles. Since the box has 4 coordinates, we can arrange them like so to form a rectangle from two triangles.
To render the triangles, we’ll convert each lat/lng from our box into clip-space, and construct an array with each of the vertices for the triangles (so 6 points in total).
const [nw_x, nw_y] = MercatorCoordinate.fromLngLat(USA_BBOX[0]);
const [ne_x, ne_y] = MercatorCoordinate.fromLngLat(USA_BBOX[1]);
const [se_x, se_y] = MercatorCoordinate.fromLngLat(USA_BBOX[2]);
const [sw_x, sw_y] = MercatorCoordinate.fromLngLat(USA_BBOX[3]);
const positions = [
// triangle 1
nw_x, nw_y,
ne_x, ne_y,
se_x, se_y,
// triangle 2
se_x, se_y,
sw_x, sw_y,
nw_x, nw_y,
];
Now that we have our vertices, we need to render it to a <canvas>.
Unfortunately, there is a lot of boilerplate needed to setup a WebGL scene, so I’ll document most of this in the code snippet below. But the gist is:
After doing all that, you can see the rectangle in the upper-left quadrant of the grid. This is where we'd expect it to be based on the image we've been using as a reference so far. You can also toggle the map on to check that it's rendered correctly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import MercatorCoordinate from './mercator-coordinate';
import { createShader, createProgram } from './webgl-utils';
//////////////////////
// constants
//////////////////////
const USA_BBOX = [
[-126.03515625, 23.079731762449878],
[-60.1171875, 23.079731762449878],
[-60.1171875, 50.233151832472245],
[-126.03515625, 50.233151832472245]
];
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0, 1);
}
`;
// color is constant for all vertices
const fragmentShaderSource =`
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 0.5, 0.5);
}
`;
//////////////////////
// main program
//////////////////////
const run = (canvasId) => {
// get GL context from canvas
const canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
// create buffer for vertices
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// add vertices to buffer
const [nw_x, nw_y] = MercatorCoordinate.fromLngLat(USA_BBOX[0]);
const [ne_x, ne_y] = MercatorCoordinate.fromLngLat(USA_BBOX[1]);
const [se_x, se_y] = MercatorCoordinate.fromLngLat(USA_BBOX[2]);
const [sw_x, sw_y] = MercatorCoordinate.fromLngLat(USA_BBOX[3]);
const positions = [
// triangle 1
nw_x, nw_y,
ne_x, ne_y,
se_x, se_y,
// triangle 2
se_x, se_y,
sw_x, sw_y,
nw_x, nw_y,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// enable on the position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
const draw = () => {
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = 6;
gl.drawArrays(primitiveType, offset, count);
}
draw();
};
export default run;
To have a useful map, we’ll also want the ability to move around. We can add some basic map behaviors such as pan & zoom.
To do this, we’ll need to introduce the idea of a “camera” for moving the viewport around the scene. This differs from a traditional camera, in that instead of moving the camera around, we’ll actually move the world around the camera. For instance, if we want to pan to the left, we’ll actually move all the vertices in our scene to the right by that same amount (we’re basically inverting the behavior we’d expect).
For our purposes, the camera will keep track of the XY position, and the current zoom level. These will then be represented as vectors, that when applied to a matrix (ie. the projection matrix) will make up the final state of the scene.
We can think of each vertex on our map as vector with three points: [x, y, z]. The idea behind using a matrix is that we can multiply the vector by the matrix to get the new vector position. For instance, if we take our vertices from above and multiply them by the identity matrix, we can see we get the same result (ie. no transformation).
If we wanted to pan the map to the right, we need to translate all of the vertices by the same amount the mouse has moved (in this case, in the x+ direction). So if the map was panned 20 pixels to the right, we’d convert that 20px to clip-space (0.92), and can represent the translation with the following matrix.
Similarly, if we wanted to apply a zoom, we can add a scale factor that gets multiplied to the vertices. For zooming, that factor is 2zoom. So if we at a zoom level of 1, our scale factor is 2.
One other caveat with zoom, if we want to zoom in on the mouse position, we'll need to grab the pre & post transformation positions of where the mouse is, and translate accordingly. There's a great article at webglfundamentals.org that covers this in depth, so I won't go into too much detail there.
The matrix containing the scale and translation values is what we’ll then pass into our vertex shader, so these vertex computations can be done on the GPU.
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
Once we setup the event handlers and update our matrix, we should be able to pan & zoom the bounding box. I'm using the glMatrix library to handle the matrix math.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { mat3, vec3 } from 'gl-matrix';
import MercatorCoordinate from './mercator-coordinate';
import { createShader, createProgram } from './webgl-utils';
//////////////////////
// constants
//////////////////////
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
const USA_BBOX = [
[-126.03515625, 23.079731762449878],
[-60.1171875, 23.079731762449878],
[-60.1171875, 50.233151832472245],
[-126.03515625, 50.233151832472245]
];
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// color is constant for all vertices
const fragmentShaderSource =`
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 0.5, 0.5);
}
`;
//////////////////////
// map state
//////////////////////
const camera = {
x: 0,
y: 0,
zoom: 0,
};
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
mat3.scale(cameraMat, cameraMat, [zoomScale, zoomScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
updateMatrix();
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e, canvas) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
//////////////////////
// main program
//////////////////////
const run = (canvasId) => {
// get GL context from canvas
const canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
// create buffer for vertices
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// add vertices to buffer
const [nw_x, nw_y] = MercatorCoordinate.fromLngLat(USA_BBOX[0]);
const [ne_x, ne_y] = MercatorCoordinate.fromLngLat(USA_BBOX[1]);
const [se_x, se_y] = MercatorCoordinate.fromLngLat(USA_BBOX[2]);
const [sw_x, sw_y] = MercatorCoordinate.fromLngLat(USA_BBOX[3]);
const positions = [
// triangle 1
nw_x, nw_y,
ne_x, ne_y,
se_x, se_y,
// triangle 2
se_x, se_y,
sw_x, sw_y,
nw_x, nw_y,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// enable on the position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
const draw = () => {
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = 6;
gl.drawArrays(primitiveType, offset, count);
}
draw(); // initial draw
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent, canvas);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// save current pos for next movement
startX = x;
startY = y;
// update matrix with new camera and redraw scene
updateMatrix();
draw();
};
const handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent, canvas);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
const handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent, canvas);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const zoomDelta = -wheelEvent.deltaY * (1 / 300);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
draw();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
};
export default run;
Let’s now take a stab at rendering something a little more complex than a rectangle. For instance, this polygon of Washington state (my home state!)
Like the rectangle, we’ll also need to divide the shape up into triangles, though it’s a little less obvious how to do that for a shape of this complexity. Fortunately, there are a number of libraries that do just that. We’ll use Mapbox’s earcut, since it has support for GeoJSON geometries out-of-the-box.
To use earcut, we’ll first need to flatten the polygon into a single array of coordinates, and then pass that into the earcut for triangulation. The result is an array of indices for how to draw the triangles. One thing to note, each point in triangles array is for both the latitude & longitude, so you’ll need to get the vertices from vertices[i] and vertices[i + 1].
// convert a GeoJSON geometry to webgl vertices
const geometryToVertices = (geometry) => {
const data = earcut.flatten(geometry.coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
Now that we have our vertices, let’s swap that out for our bounding box from earlier. We'll also need to set the initial camera position to be closer to the actual geometry. We can see the triangles by changing the primitive type to gl.LINES.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import MercatorCoordinate from './mercator-coordinate';
import { createShader, createProgram } from './webgl-utils';
//////////////////////
// constants
//////////////////////
import WASHINGTON from '../data/washington.json';
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// color is constant for all vertices
const fragmentShaderSource =`
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 0.5, 0.9);
}
`;
//////////////////////
// map state
//////////////////////
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation
camera.x = -0.6718187712249346;
camera.y = 0.29662864586475735;
camera.zoom = 5;
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
mat3.scale(cameraMat, cameraMat, [zoomScale, zoomScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
updateMatrix();
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e, canvas) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const data = earcut.flatten(geometry.coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
//////////////////////
// main program
//////////////////////
const run = (canvasId) => {
// get GL context from canvas
const canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
// create buffer for vertices
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// add vertices to buffer
const vertices = geometryToVertices(WASHINGTON);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// enable on the position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
const draw = () => {
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
}
draw(); // initial draw
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent, canvas);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// save current pos for next movement
startX = x;
startY = y;
// update matrix with new camera and redraw scene
updateMatrix();
draw();
}
const handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent, canvas);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
const handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent, canvas);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const zoomDelta = -wheelEvent.deltaY * (1 / 300);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
draw();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
};
export default run;
And if we want to do render a MultiPolygon, we can just combine the vertices from each polygon into a single array.
const geometryToVertices = (geometry) => {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
// concat all vertices from each polygon
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
positions.push(...verticesFromPolygon([polygon[0]], i));
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import MercatorCoordinate from './mercator-coordinate';
import { createShader, createProgram } from './webgl-utils';
//////////////////////
// constants
//////////////////////
import USA from '../data/usa_polygon.json';
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// color is constant for all vertices
const fragmentShaderSource =`
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 0.5, 0.5);
}
`;
//////////////////////
// map state
//////////////////////
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation
camera.x = -0.6585079014803341;
camera.y = 0.3261614716054737;
camera.zoom = 1.64;
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
mat3.scale(cameraMat, cameraMat, [zoomScale, zoomScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
updateMatrix();
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e, canvas) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
const vertices = verticesFromPolygon([polygon[0]], i);
// doing an array.push with too many values can cause
// stack size errors, so we manually iterate and append
vertices.forEach((vertex) => {
positions[positions.length] = vertex;
});
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
//////////////////////
// main program
//////////////////////
const run = (canvasId) => {
// get GL context from canvas
const canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
// create buffer for vertices
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// add vertices to buffer
const vertices = geometryToVertices(USA.geometry);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// enable on the position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
const draw = () => {
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
}
draw(); // initial draw
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent, canvas);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// save current pos for next movement
startX = x;
startY = y;
// update matrix with new camera and redraw scene
updateMatrix();
draw();
}
const handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent, canvas);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
const handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent, canvas);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const zoomDelta = -wheelEvent.deltaY * (1 / 300);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
draw();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
};
export default run;
At this point, we have a pretty solid foundation for our map. We can pan, zoom, and render complex geometries. In Part 2, will cover adding vector tile support.
In Part 1 we created a map that can render GeoJSON polygons. While this is fine if you’re rendering a handful of geometries, it doesn’t scale well if you want to render many more layers, and across the whole planet. For instance, if we wanted to display every building in the US, we'd need to load and render millions (or hundreds of millions) of vertices for the scene.
This is where tiling comes in. I cover this a bit in previous articles, but the idea is the world is broken down into a grid at each zoom level, so we only need to load the data visible in our viewport.
For these examples, we'll be using a tile size of 512px (meaning each tile is 512 X 512 pixels).
The first thing to do, is figure out which tiles are in view given our viewport. To do this, we can figure out the lat/lng position of each corner of our viewport (we’ll need to do some conversion math to go from the screen pixel to lat/lng). Once we have a lat/lng and zoom level, we can use that to determine which tile it’s in.
Mapbox has a nice utility library tilebelt for doing these lookups. We can use pointToTile to lookup the min & max tiles once we know the bounding box of our viewport.
// get bbox from viewport
const bbox = getBounds();
// find min and max tiles
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); // top-left
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // bottom-right
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
One thing to keep in mind, is our viewport might be larger than 2 tiles (> 1024px) so we’ll probably want to consider all tiles between the min and max as “in view”. For example, we could have something like the image below, where the viewport bounding box spans 12 tiles, even though they aren't all fully in view.
As we move the map around, the tiles in view should update. Panning left & right should change the tiles in view once we cross a border.
Zooming in & out though is where the real “magic” of a vector map comes into play. Instead of jumping between discrete levels (1, 2, 3 etc…) we can just scale the geometries according to the zoom values in between integers (ie. 1.25 … 1.98). Once we cross into a new zoom integer, we’ll need load a new set of tiles based on that level.
The best way to see how this works in action is to render the tile boundaries as we move around the map. We can use the code above for finding the tiles in view, and run them through tilebel.tileToGeoJSON to render them on the map.
Now that we have a way to determine which tiles are in view, we can go ahead and fetch the vector data from a tileserver.
I covered setting up a vector tile server in a previous article, so I’m going to reuse the existing tile server from there. We just need to replace the x, y, and z values in the URL to fetch the correct tiles.
`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf`
You’ll notice the URL ends with .pbf, so we’ll be getting the data back in Protobuf format. This is a binary format, that we’ll need to deserialize into an object that we can use. Fortunately mapbox has a library that does this for us. @mapbox/vector-tile can deserialize PBF data into a VectorTile object according to the vector tile spec.
const [x, y, z] = tile;
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf`, {
responseType: 'arraybuffer',
});
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
If we inspect a tile, we can see a .layers field, which contains all the different layers we can potentially render for that tile.
Object.keys(vectorTile.layers);
// ['water', 'waterway', 'landcover', 'landuse', 'park', 'boundary', 'transportation', 'building', 'water_name', 'transportation_name', 'place', 'poi', 'aerodrome_label']
You’ll notice VectorTile also has a toGeoJSON function that we can call on each feature in the layer. As we demonstrated in Part 1, we have the ability to render a GeoJSON polygon using earcut. Given that, we should be able to render tiles using the following process:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import axios from 'axios';
import Protobuf from 'pbf';
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import tilebelt from '@mapbox/tilebelt';
import { VectorTile } from '@mapbox/vector-tile';
import MercatorCoordinate from './mercator-coordinate';
import { createShader, createProgram } from './webgl-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
};
let tileKey;
let tilesInView = [];
let tileData = {}; // tile -> layers
async function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// load tile features from server
const key = tilesInView.map(t => t.join('/')).join(';');
if (tileKey !== key) { // tile changed
tileData = {};
// process each tile
const tileReqs = tilesInView.map(async (tile) => {
const [x, y, z] = tile;
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf?apiKey=${config('mapsApiKey')}`, {
responseType: 'arraybuffer',
});
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
// process only the layers we are using
const layers = {}; // layers -> features
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
const features = [];
for (let i = 0; i < numFeatures; i++) {
// get geojson representation of tile
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
// vertices for feature
const vertices = geometryToVertices(geojson.geometry);
// add to features
features.push(vertices);
}
// store features in layer
layers[layer] = features;
}
});
// store layers for tile
tileData[tile.join('/')] = layers;
});
await Promise.all(tileReqs); // run concurrently
tileKey = key;
}
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
const vertices = verticesFromPolygon([polygon[0]], i);
// doing an array.push with too many values can cause
// stack size errors, so we manually iterate and append
vertices.forEach((vertex) => {
positions[positions.length] = vertex;
});
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
const run = (canvasId) => {
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup initial state
updateMatrix();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
const draw = async () => {
await updateTiles(); // load tiles
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
Object.keys(tileData).forEach((tile) => {
Object.keys(LAYERS).forEach((layer) => {
const features = tileData[tile][layer];
const color = LAYERS[layer].map((n) => n / 255); // RGBA to WebGL color
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// render each feature
(features || []).forEach((feature) => {
// create buffer for vertices
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, feature, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = feature.length / 2;
gl.drawArrays(primitiveType, offset, count);
});
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
}
draw(); // initial draw
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
draw();
}
const handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
const handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
draw();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
};
export default run;
If you’re familiar with New York City, you should be able to make out the outline of the waterways and the parks. You’ll also notice some flashing, and lag when maneuvering around some of the more complex shapes. This is still a pretty rough implementation, and we’ll cover some performance enhancements and optimizations in Part 3.
Part 2 of this series left off with a working map that can render geometries from a vector tile server. However, the experience is still rather laggy and has some unpleasant flashes of content. Up to this point, we’ve also just been writing the map code as one-off scripts, with most the values hard-coded.
In this part, we’ll address these performance issues, as well as refactor our code into a more generic, reusable library.
Up to now, we’ve just been re-rendering the map whenever there is an interaction, such as a pan or zoom. While this does save us some CPU cycles to not have the canvas constantly re-drawing, it does have some UX implications, especially when it comes to loading the tiles asynchronously.
Rather than calling draw() whenever a state change happens, we’ll just use window.requestAnimationFrame to let the browser render the frame when ready. So when panning & zooming, we’ll just make updates to the camera & matrix values, and those changes will get picked up in the next loop.
A similar approach can also be used for loading the tiles. Instead of awaiting for all the responses to complete and blocking the loop, we can just update the tile data for each request as it completes. So tile requests that are quicker, will get rendered earlier.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import axios from 'axios';
import Protobuf from 'pbf';
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import tilebelt from '@mapbox/tilebelt';
import { VectorTile } from '@mapbox/vector-tile';
import MercatorCoordinate from './mercator-coordinate';
import Stats from 'stats.js';
import { createShader, createProgram } from './webgl-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
let loopRunning = true;
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
let statsWidget;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
};
let tileKey;
let tilesInView = [];
let tileData = {}; // tile -> layers
function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// load tile features from server
const key = tilesInView.map(t => t.join('/')).join(';');
if (tileKey !== key) { // tile changed
tileData = {};
// process each tile concurrently, and update data on complete
tilesInView.forEach(async (tile) => {
const [x, y, z] = tile;
const reqStart = Date.now();
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf?apiKey=${config('mapsApiKey')}`, {
responseType: 'arraybuffer',
});
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
// process only the layers we are using
const layers = {}; // layers -> features
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
const features = [];
for (let i = 0; i < numFeatures; i++) {
// get geojson representation of tile
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
// vertices for feature
const vertices = geometryToVertices(geojson.geometry);
// add to features
features.push(vertices);
}
// store features in layer
layers[layer] = features;
}
});
// store layers for tile
tileData[tile.join('/')] = layers;
});
tileKey = key;
}
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
positions.push(...verticesFromPolygon([polygon[0]], i));
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
let handlePan;
let handleZoom;
let timestamp;
let slowCount;
let frameStats;
const run = (canvasId, mobile, abort) => {
// setup loop state
loopRunning = true;
timestamp = 0;
slowCount = 0;
// create stats object for widget
const stats = new Stats();
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup initial state
updateMatrix();
updateTiles();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
// create buffer
const positionBuffer = gl.createBuffer();
const draw = () => {
frameStats = { drawCalls: 0, vertices: 0, features: 0 };
stats.begin();
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
Object.keys(tileData).forEach((tile) => {
Object.keys(LAYERS).forEach((layer) => {
const features = tileData[tile][layer];
const color = LAYERS[layer].map((n) => n / 255); // RGBA to WebGL color
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// render each feature
(features || []).forEach((feature) => {
frameStats.features++;
// create buffer for vertices
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, feature, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = feature.length / 2;
gl.drawArrays(primitiveType, offset, count);
frameStats.drawCalls++;
frameStats.vertices+= feature.length;
});
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
// kill loop on mobile
if (mobile) {
stop();
if (abort) {
abort();
}
return;
}
// kill loop if gets too slow
// 5 frames under 10 FPS
const now = performance.now();
const fps = 1 / ((now - timestamp) / 1000);
if (fps < 10) {
slowCount++;
if (slowCount > 5) {
console.warn(`Too slow. Killing loop for ${canvasId}.`);
stop();
if (abort) {
abort();
}
}
}
timestamp = now;
// end of loop
stats.end();
if (loopRunning) {
window.requestAnimationFrame(draw);
}
}
window.requestAnimationFrame(draw); // start loop
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
updateTiles();
}
handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_TILE_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
updateTiles();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
// setup stats widget
stats.showPanel(0); // frame rate
statsWidget = stats.dom;
statsWidget.style.position = 'absolute';
statsWidget.style.left = mobile ? 0 : '-100px';
statsWidget.style.zIndex = '0';
canvas.parentElement.appendChild(statsWidget);
};
export const stop = () => {
loopRunning = false;
// clear event handlers
if (canvas) {
canvas.removeEventListener('wheel', handleZoom);
canvas.removeEventListener('mousedown', handlePan);
overlay.replaceChildren();
statsWidget.remove();
}
};
// get the latest frame stats
export const getFrameStats = () => {
return frameStats;
}
export default run;
Now that we’re loading the tiles concurrently, you'll notice the flashing happening on a per-tile basis, rather than all-at-once. However, you might have got into a state where the map was killed (trying not to crash your browser!).
Since we’re now calling draw many times per second (ideally 60), we are making a ton of calls to shuffle data into GPU. For instance, here are the stats for the most recent frame that was rendered:
// last render stats no. of gl draw calls: undefined no. of vertices: undefined
That means for each frame, it needs to buffer data into WebGL times. Which is (probably) a lot, considering we're trying to aim for 60 frames per second.
To fix this, we can cut down the number of times we're buffering data into the GPU.
In the current approach, we’re storing the vertices for each individual feature, for each layer, for each tile. In other words our tileData, which is storing the data per-tile, looks something like:
tileData: { '1/1/1': { layer_1: [ feature_1 vertices, feature_2 vertices, … feature_n vertices, ], … // more layers }, '1/1/2': { … } … // more tiles }
Since all the features for a given layer are rendered the same (ie. same color), we can just combine all of the feature vertices into a single array for the layer. This will cut down the number of times we need to reset the buffers and call gl.drawArrays to once per layer, per tile. So our new tileData structure will look something like:
tileData: { '1/1/1': [ { layer: ‘layer_1’, vertices: […] }, { layer: ‘layer_2’, vertices: […] }, … ] … }
And the updated code that processes the tile:
const layers = [];
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
// concat vertices for all features of layer so they can all be rendered at once
const vertices = [];
for (let i = 0; i < numFeatures; i++) {
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
vertices.push(...geometryToVertices(geojson.geometry)); // concat all vertices
}
layers.push({ layer, vertices: Float32Array.from(vertices) });
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
import axios from 'axios';
import Protobuf from 'pbf';
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import tilebelt from '@mapbox/tilebelt';
import { VectorTile } from '@mapbox/vector-tile';
import MercatorCoordinate from './mercator-coordinate';
import Stats from 'stats.js';
import { createShader, createProgram } from './webgl-utils';
import { append } from './array-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
let loopRunning = true;
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
let statsWidget;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
building: [185, 175, 139, 191],
};
let tileKey;
let tilesInView = [];
let tileData = {}; // tile -> layers
function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// load tile features from server
const key = tilesInView.map(t => t.join('/')).join(';');
if (tileKey !== key) { // tile changed
tileData = {};
// process each tile concurrently, and update data on complete
tilesInView.forEach(async (tile) => {
const [x, y, z] = tile;
const reqStart = Date.now();
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf?apiKey=${config('mapsApiKey')}`, {
responseType: 'arraybuffer',
});
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
// process only the layers we are using
const layers = [] // layers -> features
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
const vertices = [];
for (let i = 0; i < numFeatures; i++) {
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
append(vertices, geometryToVertices(geojson.geometry));
}
layers.push({ layer, vertices: Float32Array.from(vertices) });
}
});
// store layers for tile
tileData[tile.join('/')] = layers;
});
tileKey = key;
}
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
append(positions, verticesFromPolygon([polygon[0]], i));
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
let handlePan;
let handleZoom;
let timestamp;
let slowCount;
let frameStats;
const run = (canvasId, mobile, abort) => {
// setup loop state
loopRunning = true;
timestamp = 0;
slowCount = 0;
// create stats object for widget
const stats = new Stats();
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup initial state
updateMatrix();
updateTiles();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.clearColor(0, 0, 0, 0);
gl.useProgram(program);
// create buffer
const positionBuffer = gl.createBuffer();
const draw = () => {
frameStats = { drawCalls: 0, vertices: 0 };
stats.begin();
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
Object.keys(tileData).forEach((tile) => {
tileData[tile].forEach((tileLayer) => {
const { layer, vertices } = tileLayer;
if (LAYERS[layer]) {
const color = LAYERS[layer].map(n => n / 255);
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// create buffer for vertices
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
frameStats.drawCalls++;
frameStats.vertices+= vertices.length;
}
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
// kill loop if gets too slow
// 10 frames under 10 FPS
const now = performance.now();
const fps = 1 / ((now - timestamp) / 1000);
if (fps < 10) {
slowCount++;
if (slowCount > 10) {
console.warn(`Too slow. Killing loop for ${canvasId}.`);
stop();
if (abort) {
abort();
}
}
}
timestamp = now;
// end of loop
stats.end();
if (loopRunning) {
window.requestAnimationFrame(draw);
}
}
window.requestAnimationFrame(draw); // start loop
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
updateTiles();
}
handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
updateTiles();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
// setup stats widget
stats.showPanel(0); // frame rate
statsWidget = stats.dom;
statsWidget.style.position = 'absolute';
statsWidget.style.left = mobile ? 0 : '-100px';
statsWidget.style.zIndex = '0';
canvas.parentElement.appendChild(statsWidget);
};
export const stop = () => {
loopRunning = false;
// clear event handlers
if (canvas) {
canvas.removeEventListener('wheel', handleZoom);
canvas.removeEventListener('mousedown', handlePan);
overlay.replaceChildren();
statsWidget.remove();
}
};
// get the latest frame stats
export const getFrameStats = () => {
return frameStats;
}
export default run;
You’ll notice the frame rate is consistently much higher, and navigating is much smoother. In fact, the jump in performance was high enough that we easily added an additional buildings layer (the brown-ish rectangles rendered at high zoom levels).
// last render stats no. of gl draw calls: undefined no. of vertices: undefined
Even though the frame rate is higher, we’re still getting some flashing when loading the tiles, so let’s address that next.
The tile flashing is a relatively simple fix. In our updateTiles code, we just need to check if we’ve already loaded that tile at some point, and just re-use the data if it already exists (instead of fetching it from the server).
// process each tile concurrently, and update data on complete
tilesInView.forEach(async (tile) => {
if (tileData[tile.join('/')]) {
return; // already loaded, no need to fetch
}
const [x, y, z] = tile;
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf`, {
responseType: 'arraybuffer',
});
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
import axios from 'axios';
import Protobuf from 'pbf';
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import tilebelt from '@mapbox/tilebelt';
import { VectorTile } from '@mapbox/vector-tile';
import MercatorCoordinate from './mercator-coordinate';
import Stats from 'stats.js';
import { createShader, createProgram } from './webgl-utils';
import { append } from './array-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
let loopRunning = true;
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
let statsWidget;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
building: [185, 175, 139, 191],
};
let tilesInView = [];
let tileData = {}; // tile -> layers
let cacheStats = { tilesLoaded: 0, cacheHits: 0 };
function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// process each tile concurrently, and update data on complete
tilesInView.forEach(async (tile) => {
if (tileData[tile.join('/')]) {
cacheStats.cacheHits++;
return; // already loaded, no need to fetch
}
const [x, y, z] = tile;
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf?apiKey=${config('mapsApiKey')}`, {
responseType: 'arraybuffer',
});
cacheStats.tilesLoaded++;
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
// process only the layers we are using
const layers = [] // layers -> features
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
const vertices = [];
for (let i = 0; i < numFeatures; i++) {
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
append(vertices, geometryToVertices(geojson.geometry));
}
layers.push({ layer, vertices: Float32Array.from(vertices) });
}
});
// store layers for tile
tileData[tile.join('/')] = layers;
});
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
append(positions, verticesFromPolygon([polygon[0]], i));
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
let handlePan;
let handleZoom;
let timestamp;
let slowCount;
let frameStats;
const run = (canvasId, mobile, abort) => {
// setup loop state
loopRunning = true;
timestamp = 0;
slowCount = 0;
// create stats object for widget
const stats = new Stats();
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup initial state
updateMatrix();
updateTiles();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.useProgram(program);
gl.clearColor(0, 0, 0, 0);
// create buffer
const positionBuffer = gl.createBuffer();
const draw = () => {
frameStats = { drawCalls: 0, vertices: 0 };
stats.begin();
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
tilesInView.forEach((tile) => {
const data = tileData[tile.join('/')];
(data || []).forEach((tileLayer) => {
const { layer, vertices } = tileLayer;
if (LAYERS[layer]) {
const color = LAYERS[layer].map(n => n / 255);
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// create buffer for vertices
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
frameStats.drawCalls++;
frameStats.vertices+= vertices.length;
}
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
// kill loop if gets too slow
// 10 frames under 10 FPS
const now = performance.now();
const fps = 1 / ((now - timestamp) / 1000);
if (fps < 10) {
slowCount++;
if (slowCount > 10) {
console.warn(`Too slow. Killing loop for ${canvasId}.`);
stop();
if (abort) {
abort();
}
}
}
timestamp = now;
// end of loop
stats.end();
if (loopRunning) {
window.requestAnimationFrame(draw);
}
}
window.requestAnimationFrame(draw); // start loop
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
updateTiles();
}
handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
updateTiles();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
// setup stats widget
stats.showPanel(0); // frame rate
statsWidget = stats.dom;
statsWidget.style.position = 'absolute';
statsWidget.style.left = mobile ? 0 : '-100px';
statsWidget.style.zIndex = '0';
canvas.parentElement.appendChild(statsWidget);
};
export const stop = () => {
loopRunning = false;
// clear event handlers
if (canvas) {
canvas.removeEventListener('wheel', handleZoom);
canvas.removeEventListener('mousedown', handlePan);
overlay.replaceChildren();
statsWidget.remove();
}
};
// get the latest frame stats
export const getCacheStats = () => {
return cacheStats;
}
export default run;
As we move around, we can see how many requests we're saving by not refetching tiles already loaded. There's still some flashing the first time a tile is loaded, but cached tiles should render seamlessly when moving between them.
tiles loaded: undefined cache hits: undefined
Now that we’ve solved the issue of repeatedly flashing tiles, let's clean up the flash on the initial load, that can sometimes be seen when moving the map quickly.
We know that cached tiles will render seamlessly when moved back into view, so we can actually pre-load tiles that are near the viewport (ie. tiles we will likely navigate into).
We just need to configure how much we want to buffer. For now, let's just load an additional tile in each direction (min - 1, max + 1) to make sure the nearest tiles are covered for panning, as well as the parent (tiles above). We'll talk about the child tiles in the next section.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import axios from 'axios';
import Protobuf from 'pbf';
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import tilebelt from '@mapbox/tilebelt';
import { VectorTile } from '@mapbox/vector-tile';
import MercatorCoordinate from './mercator-coordinate';
import Stats from 'stats.js';
import { createShader, createProgram } from './webgl-utils';
import { append } from './array-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
let loopRunning = true;
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
let statsWidget;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
building: [185, 175, 139, 191],
};
const TILE_BUFFER = 1; // 1 tile in each direction
let tilesInView = [];
let tileData = {}; // tile -> layers
let cacheStats = { tilesLoaded: 0, cacheHits: 0 };
function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// load additional tiles outside of viewport
const bufferedTiles = [];
for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) {
for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) {
bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction
// load parent tiles 2 levels up
bufferedTiles.push(tilebelt.getParent([bufX, bufY, z]));
bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z])));
}
}
// remove dupes (and convert to strings)
let tilesToLoad = [
...new Set([
...tilesInView.map(t => t.join('/')),
...bufferedTiles.map(t => t.join('/'))
])
];
// make sure tiles are in range
tilesToLoad = tilesToLoad.filter((tile) => {
const [x, y, z] = tile.split('/').map(Number);
const N = Math.pow(2, z);
const validX = x >= 0 && x < N;
const validY = y >= 0 && y < N;
const validZ = z >= 0 && z <= MAX_TILE_ZOOM;
return validX && validY && validZ;
});
// process each tile concurrently, and update data on complete
tilesToLoad.forEach(async (tile) => {
if (tileData[tile]) {
cacheStats.cacheHits++;
return; // already loaded, no need to fetch
} else {
tileData[tile] = []; // temp hold for request
}
try {
const [x, y, z] = tile.split('/').map(Number);
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf?apiKey=${config('mapsApiKey')}`, {
responseType: 'arraybuffer',
});
cacheStats.tilesLoaded++;
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
// process only the layers we are using
const layers = [] // layers -> features
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
const vertices = [];
for (let i = 0; i < numFeatures; i++) {
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
append(vertices, geometryToVertices(geojson.geometry));
}
layers.push({ layer, vertices: Float32Array.from(vertices) });
}
});
// store layers for tile
tileData[tile] = layers;
} catch (e) {
console.warn(`Tile ${tile} request failed.`, e);
tileData[tile] = undefined; // release hold
}
});
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
positions.push(...verticesFromPolygon([polygon[0]], i));
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
let handlePan;
let handleZoom;
let frameStats;
let slowCount;
let timestamp;
const run = (canvasId, mobile, abort) => {
// setup loop state
loopRunning = true;
timestamp = 0;
slowCount = 0;
// create stats object for widget
const stats = new Stats();
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup initial state
updateMatrix();
updateTiles();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.useProgram(program);
gl.clearColor(0, 0, 0, 0);
// create buffer
const positionBuffer = gl.createBuffer();
const draw = () => {
frameStats = { drawCalls: 0, vertices: 0 };
stats.begin();
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
tilesInView.forEach((tile) => {
const data = tileData[tile.join('/')];
(data || []).forEach((tileLayer) => {
const { layer, vertices } = tileLayer;
if (LAYERS[layer]) {
const color = LAYERS[layer].map(n => n / 255);
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// create buffer for vertices
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
frameStats.drawCalls++;
frameStats.vertices+= vertices.length;
}
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
// kill loop if gets too slow
// 10 frames under 10 FPS
const now = performance.now();
const fps = 1 / ((now - timestamp) / 1000);
if (fps < 10) {
slowCount++;
if (slowCount > 10) {
console.warn(`Too slow. Killing loop for ${canvasId}.`);
stop();
if (abort) {
abort();
}
}
}
timestamp = now;
// end of loop
stats.end();
if (loopRunning) {
window.requestAnimationFrame(draw);
}
}
window.requestAnimationFrame(draw); // start loop
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
updateTiles();
}
handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
updateTiles();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
// setup stats widget
stats.showPanel(0); // frame rate
statsWidget = stats.dom;
statsWidget.style.position = 'absolute';
statsWidget.style.left = mobile ? 0 : '-100px';
statsWidget.style.zIndex = '0';
canvas.parentElement.appendChild(statsWidget);
};
export const stop = () => {
loopRunning = false;
// clear event handlers
if (canvas) {
canvas.removeEventListener('wheel', handleZoom);
canvas.removeEventListener('mousedown', handlePan);
overlay.replaceChildren();
statsWidget.remove();
}
};
// get the latest frame stats
export const getCacheStats = () => {
return cacheStats;
}
export default run;
With the exception of zooming in/out really quickly, the flashing should be greatly reduced when moving around. But we can take it a step further by scaling the data we already have to fill in missing tiles.
The last thing we’ll do to prevent the flashing you see when zooming, is to just keep scaling the data that we already have in place of tiles that are still downloading.
Take zooming in for example. If we’re on zoom level 8, we will keep scaling the tiles up until we hit zoom level 9, at which point we render the level 9 tiles in view. But if those aren’t done being downloaded and parsed yet, we’ll see a white square in its place. So what we can do, is continue to scale the level 8 tile up in its place, until we have the data for the correct tile (ie. we’ll still be rendering the level 8 tile at 9+).
Similarly with zooming out, we can render all of the children for a tile if the one at the lower level isn’t available. This one is a bit more noticeable, since as we zoom out, we might only have partial children available for a parent tile. Take the screenshot below for instance, notice that not all of the child tiles are available. So while still not perfect, it’s slight improvement on the whole tile being blank.
To accomplish this, we just need to introduce some fallback behavior for when tile data from tileInView is not available. We’ll favor the case where the parent tile is available, since that will always cover more area, but we can still fallback to the child tiles in cases where we’re zooming out.
We can leverage the tilebelt library again for determining the parent tilebel.getParent and children tilebelt.getChildren tiles.
function getPlaceholderTile(tile) {
// use parent if available
const parent = tilebelt.getParent(tile)?.join('/');
const parentFeatureSet = tileData[parent];
if (parentFeatureSet?.length > 0) {
return parentFeatureSet;
}
// use whatever children are available
const childFeatureSets = [];
const children = (tilebelt.getChildren(tile) || []).map(t => t.join('/'));
children.forEach((child) => {
const featureSet = tileData[child];
if (featureSet?.length > 0) {
childFeatureSets.push(...featureSet);
}
});
return childFeatureSets;
}
...
// in draw:
tilesInView.forEach((tile) => {
let data = tileData[tile.join('/')];
// use placehodler if tile in view is not available
if (data?.length === 0) {
data = getPlaceholderTile(tile);
}
(data || []).forEach((tileLayer) => {
// ... render code
}
And adding this fallback behavior to our code, should provide a smoother experience (ie. fewer flashes) as we move around the map.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
import axios from 'axios';
import Protobuf from 'pbf';
import { mat3, vec3 } from 'gl-matrix';
import earcut from 'earcut';
import tilebelt from '@mapbox/tilebelt';
import { VectorTile } from '@mapbox/vector-tile';
import MercatorCoordinate from './mercator-coordinate';
import Stats from 'stats.js';
import { createShader, createProgram } from './webgl-utils';
import { append } from './array-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
let loopRunning = true;
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
let statsWidget;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
building: [185, 175, 139, 191],
};
const TILE_BUFFER = 1; // 1 tile in each direction
let tilesInView = [];
let tileData = {}; // tile -> layers
let cacheStats = { tilesLoaded: 0, cacheHits: 0 };
function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// load additional tiles outside of viewport
const bufferedTiles = [];
for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) {
for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) {
bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction
// load parent tiles 2 levels up
bufferedTiles.push(tilebelt.getParent([bufX, bufY, z]));
bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z])));
}
}
// remove dupes (and convert to strings)
let tilesToLoad = [
...new Set([
...tilesInView.map(t => t.join('/')),
...bufferedTiles.map(t => t.join('/'))
])
];
// make sure tiles are in range
tilesToLoad = tilesToLoad.filter((tile) => {
const [x, y, z] = tile.split('/').map(Number);
const N = Math.pow(2, z);
const validX = x >= 0 && x < N;
const validY = y >= 0 && y < N;
const validZ = z >= 0 && z <= MAX_TILE_ZOOM;
return validX && validY && validZ;
});
// process each tile concurrently, and update data on complete
tilesToLoad.forEach(async (tile) => {
if (tileData[tile]) {
cacheStats.cacheHits++;
return; // already loaded, no need to fetch
} else {
tileData[tile] = []; // temp hold for request
}
try {
const [x, y, z] = tile.split('/').map(Number);
const res = await axios.get(`https://maps.ckochis.com/data/v3/${z}/${x}/${y}.pbf?apiKey=${config('mapsApiKey')}`, {
responseType: 'arraybuffer',
});
cacheStats.tilesLoaded++;
const pbf = new Protobuf(res.data);
const vectorTile = new VectorTile(pbf);
// process only the layers we are using
const layers = [] // layers -> features
Object.keys(LAYERS).forEach((layer) => {
if (vectorTile?.layers?.[layer]) {
const numFeatures = vectorTile.layers[layer]?._features?.length || 0;
const vertices = [];
for (let i = 0; i < numFeatures; i++) {
const geojson = vectorTile.layers[layer].feature(i).toGeoJSON(x, y, z);
append(vertices, geometryToVertices(geojson.geometry));
}
layers.push({ layer, vertices: Float32Array.from(vertices) });
}
});
// store layers for tile
tileData[tile] = layers;
} catch (e) {
console.warn(`Tile ${tile} request failed.`, e);
tileData[tile] = undefined; // release hold
}
});
}
function getPlaceholderTile(tile) {
// use parent if available
const parent = tilebelt.getParent(tile)?.join('/');
const parentFeatureSet = tileData[parent];
if (parentFeatureSet?.length > 0) {
return parentFeatureSet;
}
// use whatever children are available
const childFeatureSets = [];
const children = (tilebelt.getChildren(tile) || []).map(t => t.join('/'));
children.forEach((child) => {
const featureSet = tileData[child];
if (featureSet?.length > 0) {
childFeatureSets.push(...featureSet);
}
});
return childFeatureSets;
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// convert a GeoJSON geometry to webgl vertices
function geometryToVertices(geometry) {
const verticesFromPolygon = (coordinates, n) => {
const data = earcut.flatten(coordinates);
const triangles = earcut(data.vertices, data.holes, 2);
const vertices = new Float32Array(triangles.length * 2);
for (let i = 0; i < triangles.length; i++) {
const point = triangles[i];
const lng = data.vertices[point * 2];
const lat = data.vertices[point * 2 + 1];
const [x, y] = MercatorCoordinate.fromLngLat([lng, lat]);
vertices[i * 2] = x;
vertices[i * 2 + 1] = y;
}
return vertices;
}
if (geometry.type === 'Polygon') {
return verticesFromPolygon(geometry.coordinates);
}
if (geometry.type === 'MultiPolygon') {
const positions = [];
geometry.coordinates.forEach((polygon, i) => {
positions.push(...verticesFromPolygon([polygon[0]], i));
});
return Float32Array.from(positions);
}
// only support Polygon & Multipolygon for now
return new Float32Array();
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
let handlePan;
let handleZoom;
let timestamp;
let slowCount;
let frameStats;
const run = (canvasId, mobile, abort) => {
// setup loop state
loopRunning = true;
timestamp = 0;
slowCount = 0;
// create stats object for widget
const stats = new Stats();
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup initial state
updateMatrix();
updateTiles();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.useProgram(program);
gl.clearColor(0, 0, 0, 0);
// create buffer
const positionBuffer = gl.createBuffer();
const draw = () => {
frameStats = { drawCalls: 0, vertices: 0 };
stats.begin();
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
tilesInView.forEach((tile) => {
let data = tileData[tile.join('/')];
if (data?.length === 0) {
data = getPlaceholderTile(tile);
}
(data || []).forEach((tileLayer) => {
const { layer, vertices } = tileLayer;
if (LAYERS[layer]) {
const color = LAYERS[layer].map(n => n / 255);
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// create buffer for vertices
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
frameStats.drawCalls++;
frameStats.vertices+= vertices.length;
}
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
// kill loop if gets too slow
// 10 frames under 10 FPS
const now = performance.now();
const fps = 1 / ((now - timestamp) / 1000);
if (fps < 10) {
slowCount++;
if (slowCount > 10) {
console.warn(`Too slow. Killing loop for ${canvasId}.`);
stop();
if (abort) {
abort();
}
}
}
timestamp = now;
// end of loop
stats.end();
if (loopRunning) {
window.requestAnimationFrame(draw);
}
}
window.requestAnimationFrame(draw); // start loop
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
updateTiles();
}
handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
updateTiles();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
// setup stats widget
stats.showPanel(0); // frame rate
statsWidget = stats.dom;
statsWidget.style.position = 'absolute';
statsWidget.style.left = mobile ? 0 : '-100px';
statsWidget.style.zIndex = '0';
canvas.parentElement.appendChild(statsWidget);
};
export const stop = () => {
loopRunning = false;
// clear event handlers
if (canvas) {
canvas.removeEventListener('wheel', handleZoom);
canvas.removeEventListener('mousedown', handlePan);
overlay.replaceChildren();
statsWidget.remove();
}
};
// get the latest frame stats
export const getCacheStats = () => {
return cacheStats;
}
export default run;
One issue with the current approach, is the CPU overhead of running lots of requests concurrently, and parsing the geometries (which is a CPU blocking operation). For instance, the initial load of the map fires off ~30 requests to load all the buffered tiles.
tiles loaded: undefined cache hits: undefined
Since a lot of this is work that can happen in the background, we can offload it to a Web Worker to free up resources on the main thread.
The most resource heavy part of our code right now is probably the HTTP request to fetch a tile, followed by converting the geometries to vertices & triangles. Luckily, both these tasks are part of the same operation (fetch then parse), so we can pretty easily move this code to a WebWorker, which leaves the main thread free to handle the render loop, and other map interactions.
If we abstract a way the fetching / parsing code into a fetchTile helper, our worker is pretty simple:
import { fetchTile } from './map-utils';
addEventListener('message', async (event) => {
const { tile, layers, url } = event.data;
try {
const tileData = await fetchTile({ tile, layers, url });
postMessage({ tile, tileData });
} catch (e) {
console.warn('Worker error.', e);
postMessage({ tile }); // undefined tileData will unset cache hold
}
});
And then when looping through our updated tiles, we can hand them off to the worker for processing
tileWorker = new Worker(new URL('./tile-worker.js', import.meta.url));
tileWorker.onmessage = (event) => {
const { tile, tileData } = event.data;
tiles[tile] = tileData;
};
...
tilesToLoad.forEach(async (tile) => {
if (tiles[tile]) {
return; // already loaded, no need to fetch
}
tiles[tile] = []; // temp hold for request
// load buffered tiles in web worker
tileWorker.postMessage({ tile, layers: LAYERS, url: TILE_SERVER_URL });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import { mat3, vec3 } from 'gl-matrix';
import tilebelt from '@mapbox/tilebelt';
import MercatorCoordinate from './mercator-coordinate';
import Stats from 'stats.js';
import { createShader, createProgram } from './webgl-utils';
import { geometryToVertices, fetchTile } from './map-utils';
import config from '../config';
//////////////////////
// constants
//////////////////////
const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`;
const TILE_SIZE = 512;
const MAX_TILE_ZOOM = 14;
const MIN_ZOOM = 0;
const MAX_ZOOM = 16;
//////////////////////
// shaders
//////////////////////
// vertex shader just passes through the position,
// no modification to the vertices
const vertexShaderSource = `
attribute vec2 a_position;
uniform mat3 u_matrix; // 3 X 3 matrix
void main() {
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
gl_Position = vec4(position, 0, 1);
}
`;
// set color via uniform
const fragmentShaderSource =`
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
//////////////////////
// map state
//////////////////////
let loopRunning = true;
const camera = {
x: 0,
y: 0,
zoom: 0,
};
// initial transformation (Brooklyn)
camera.x = -0.41101919888888894;
camera.y = 0.2478952993354263;
camera.zoom = 13;
// DOM elements
let canvas;
let overlay;
let statsWidget;
const LAYERS = {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
building: [185, 175, 139, 191],
};
const TILE_BUFFER = 1; // 1 tile in each direction
let tiles = {}; // tile -> layers
let tilesInView = [];
let tileWorker;
function updateTiles() {
const bbox = getBounds();
const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM);
const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z);
const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z);
// tiles visible in viewport
tilesInView = [];
const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]];
const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]];
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
tilesInView.push([x, y, z]);
}
}
// load additional tiles outside of viewport
let bufferedTiles = [];
for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) {
for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) {
bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction
// load parent tiles 2 levels up
bufferedTiles.push(tilebelt.getParent([bufX, bufY, z]));
bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z])));
}
}
// remove dupes from in view
let tilesToLoad = [
...new Set([
...tilesInView.map(t => t.join('/')),
...bufferedTiles.map(t => t.join('/'))
])
];
// make sure tiles are in range
tilesToLoad = tilesToLoad.filter((tile) => {
const [x, y, z] = tile.split('/').map(Number);
const N = Math.pow(2, z);
const validX = x >= 0 && x < N;
const validY = y >= 0 && y < N;
const validZ = z >= 0 && z <= MAX_TILE_ZOOM;
return validX && validY && validZ;
});
// process each tile concurrently, and update data on complete
const inView = tilesInView.map(t => t.join('/'));
tilesToLoad.forEach(async (tile) => {
if (tiles[tile]) {
return; // already loaded, no need to fetch
}
tiles[tile] = []; // temp hold for request
try {
if (inView.includes(tile)) {
// prioritize tiles in-view on main thread (I dont know if this actually helps...)
const tileData = await fetchTile({ tile, layers: LAYERS, url: TILE_SERVER_URL });
tiles[tile] = tileData;
} else {
// load buffered tiles in worker
tileWorker.postMessage({ tile, layers: LAYERS, url: TILE_SERVER_URL }); // handle with web worker
}
} catch (e) {
console.warn(`Error loading tile ${tile}`. e);
tiles[tile] = undefined; // release hold
}
});
}
let matrix;
function updateMatrix() {
const cameraMat = mat3.create();
// translate
mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]);
// scale
const zoomScale = 1 / Math.pow(2, camera.zoom);
const widthScale = TILE_SIZE / canvas.width;
const heightScale = TILE_SIZE / canvas.height;
mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]);
// update matrix
matrix = mat3.multiply(
[],
mat3.create(), // identity matrix
mat3.invert([], cameraMat) // invert camera position
);
}
//////////////////////
// helpers
//////////////////////
function getClipSpacePosition(e) {
// handle mouse and touch events
const [x, y] = [
e.center?.x || e.clientX,
e.center?.y || e.clientY
];
// get canvas relative css position
const rect = canvas.getBoundingClientRect();
const cssX = x - rect.left;
const cssY = y - rect.top;
// get normalized 0 to 1 position across and down canvas
const normalizedX = cssX / canvas.clientWidth;
const normalizedY = cssY / canvas.clientHeight;
// convert to clip space
const clipX = normalizedX * 2 - 1;
const clipY = normalizedY * -2 + 1;
return [clipX, clipY];
}
// get bbox coordinates for viewport
function getBounds() {
const zoomScale = Math.pow(2, camera.zoom);
// undo clip-space
const px = (1 + camera.x) / 2;
const py = (1 - camera.y) / 2;
// get world coord in px
const wx = px * TILE_SIZE;
const wy = py * TILE_SIZE;
// get zoom px
const zx = wx * zoomScale;
const zy = wy * zoomScale;
// get bottom-left and top-right pixels
let x1 = zx - (canvas.width / 2);
let y1 = zy + (canvas.height / 2);
let x2 = zx + (canvas.width / 2);
let y2 = zy - (canvas.height / 2);
// convert to world coords
x1 = x1 / zoomScale / TILE_SIZE;
y1 = y1 / zoomScale / TILE_SIZE;
x2 = x2 / zoomScale / TILE_SIZE;
y2 = y2 / zoomScale / TILE_SIZE;
// get LngLat bounding box
const bbox = [
Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180),
Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05),
Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180),
Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05),
];
return bbox;
}
function atLimits() {
const bbox = getBounds();
return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05;
}
//////////////////////
// main program
//////////////////////
let handlePan;
let handleZoom;
let timestamp;
let slowCount;
let frameStats;
const run = (canvasId, mobile, abort) => {
// setup loop state
loopRunning = true;
timestamp = 0;
slowCount = 0;
// create stats object for widget
const stats = new Stats();
// get GL context from canvas
canvas = document.getElementById(canvasId);
const gl = canvas.getContext("webgl");
// get overlay
overlay = document.getElementById(`${canvasId}-overlay`);
// setup tile worker
tileWorker = new Worker(new URL('./tile-worker.js', import.meta.url));
tileWorker.onmessage = (event) => {
const { tile, tileData } = event.data;
tiles[tile] = tileData;
};
tileWorker.onerror = (error) => {
console.error('Uncaught worker error.', error);
};
// setup initial state
updateMatrix();
updateTiles();
// setup viewport
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// compile shaders
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// init gl program
const program = createProgram(gl, vertexShader, fragmentShader);
gl.useProgram(program);
gl.clearColor(0, 0, 0, 0);
// create buffer
const positionBuffer = gl.createBuffer();
const draw = () => {
frameStats = { drawCalls: 0, vertices: 0 };
stats.begin();
// set matrix as uniform
const matrixLocation = gl.getUniformLocation(program, "u_matrix");
gl.uniformMatrix3fv(matrixLocation, false, matrix);
// render tiles
tilesInView.forEach((tile) => {
const tileData = tiles[tile.join('/')];
(tileData || []).forEach((tileLayer) => {
const { layer, vertices } = tileLayer;
if (LAYERS[layer]) {
const color = LAYERS[layer].map(n => n / 255);
// set color uniform for layer
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, color);
// create buffer for vertices
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.TRIANGLES;
offset = 0;
const count = vertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
frameStats.drawCalls++;
frameStats.vertices+= vertices.length;
}
});
});
overlay.replaceChildren(); // clear labels to redraw
// render boundaries and label for tiles in view
tilesInView.forEach((tile) => {
const colorLocation = gl.getUniformLocation(program, "u_color");
gl.uniform4fv(colorLocation, [1, 0, 0, 1]);
const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile));
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW);
// setup position attribute
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(positionAttributeLocation);
// tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
const size = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
let offset = 0;
gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset);
// draw
const primitiveType = gl.LINES;
offset = 0;
const count = tileVertices.length / 2;
gl.drawArrays(primitiveType, offset, count);
// draw tile labels
const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates;
const topLeft = tileCoordinates[0][0];
const [x, y] = MercatorCoordinate.fromLngLat(topLeft);
const [clipX, clipY] = vec3.transformMat3(
[],
[x, y, 1],
matrix,
);
const wx = ((1 + clipX) / 2) * canvas.width;
const wy = ((1 - clipY) / 2) * canvas.height;
const div = document.createElement("div");
div.className = "tile-label";
div.style.left = (wx + 8) + "px";
div.style.top = (wy + 8) + "px";
div.style.position = 'absolute';
div.style.zIndex = 1000;
div.appendChild(document.createTextNode(tile.join('/')));
overlay.appendChild(div);
});
// kill loop if gets too slow
// 10 frames under 10 FPS
const now = performance.now();
const fps = 1 / ((now - timestamp) / 1000);
if (fps < 10) {
slowCount++;
if (slowCount > 10) {
console.warn(`Too slow. Killing loop for ${canvasId}.`);
stop();
if (abort) {
abort();
}
}
}
timestamp = now;
// end of loop
stats.end();
if (loopRunning) {
window.requestAnimationFrame(draw);
}
}
window.requestAnimationFrame(draw); // start loop
////////////////////////
// interaction handlers
////////////////////////
// handle touch events
const Hammer = require('hammerjs');
const hammer = new Hammer(canvas);
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammer.get('pinch').set({ enable: true });
// handle pan events
let startX;
let startY;
// handle drag changes while mouse is still down
const handleMove = (moveEvent) => {
const [x, y] = getClipSpacePosition(moveEvent);
// compute the previous position in world space
const [preX, preY] = vec3.transformMat3(
[],
[startX, startY, 0],
mat3.invert([], matrix)
);
// compute the new position in world space
const [postX, postY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// move that amount, because how much the position changes depends on the zoom level
const deltaX = preX - postX;
const deltaY = preY - postY;
if (isNaN(deltaX) || isNaN(deltaY)) {
return; // abort
}
// only update within world limits
camera.x += deltaX;
camera.y += deltaY;
// update matrix with new camera
updateMatrix();
// prevent further pan if at limits
if (atLimits()) {
camera.x -= deltaX;
camera.y -= deltaY;
updateMatrix();
return; // abort
}
// save current pos for next movement
startX = x;
startY = y;
updateMatrix();
updateTiles();
}
handlePan = (startEvent) => {
// get position of initial drag
[startX, startY] = getClipSpacePosition(startEvent);
canvas.style.cursor = 'grabbing';
window.addEventListener('mousemove', handleMove);
hammer.on('pan', handleMove);
// clear on release
const clear = (event) => {
canvas.style.cursor = 'grab';
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', clear);
hammer.off('pan', handleMove);
hammer.off('panend', clear);
};
window.addEventListener('mouseup', clear);
hammer.on('panend', clear);
}
canvas.addEventListener('mousedown', handlePan);
hammer.on('panstart', handlePan);
// handle zoom events
handleZoom = (wheelEvent) => {
wheelEvent.preventDefault();
const [x, y] = getClipSpacePosition(wheelEvent);
// get position before zooming
const [preZoomX, preZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// update current zoom state
const prevZoom = camera.zoom;
const zoomDelta = -wheelEvent.deltaY * (1 / 500);
camera.zoom += zoomDelta;
camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM));
updateMatrix();
// prevent further zoom if at limits
if (atLimits()) {
camera.zoom = prevZoom
updateMatrix();
return;
}
// get new position after zooming
const [postZoomX, postZoomY] = vec3.transformMat3(
[],
[x, y, 0],
mat3.invert([], matrix)
);
// camera needs to be translated the difference of before and after
camera.x += preZoomX - postZoomX;
camera.y += preZoomY - postZoomY;
updateMatrix();
updateTiles();
}
canvas.addEventListener('wheel', handleZoom);
hammer.on('pinch', handleZoom);
// setup stats widget
stats.showPanel(0); // frame rate
statsWidget = stats.dom;
statsWidget.style.position = 'absolute';
statsWidget.style.left = mobile ? 0 : '-100px';
statsWidget.style.zIndex = '0';
canvas.parentElement.appendChild(statsWidget);
};
export const stop = () => {
loopRunning = false;
// clear event handlers
if (canvas) {
canvas.removeEventListener('wheel', handleZoom);
canvas.removeEventListener('mousedown', handlePan);
overlay.replaceChildren();
statsWidget.remove();
}
};
// get the latest frame stats
export const getCacheStats = () => {
return cacheStats;
}
export default run;
The results aren’t that indistinguishable from the previous buffered example, probably due to the bottleneck being the latency on the http request, which is the same regardless. We could probably measure the difference in CPU, but it’s likely negligible given we’re only rendering a few layers.
Up until this point, I’ve been using a one-off JS script for every map. While this is fine for quick prototyping, it’s not very reusable, and makes it difficult to configure settings on-the-fly since most values are hard-coded.
The last piece, is wrapping this all up into a reusable library with a standard map-like interface than we can instantiate with our configuration, and easily update.
const map = new WebGLMap({
id: 'myCanvasId',
tileServerURL: 'https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf',
width: 800,
height: 600,
center: [-73.9834558, 40.6932723],
minZoom: 4,
maxZoom: 18,
zoom: 13,
debug: true,
layers: {
water: [180, 240, 250, 255],
landcover: [202, 246, 193, 255],
park: [202, 255, 193, 255],
building: [185, 175, 139, 191],
}
});
...
map.setOptions({ zoom: 10, debug: false });
You can find the code for it at webgl-map on Github as well as the demo-page built with the library.
If you’ve followed along, I hope you’ve enjoyed, or at least found it helpful. If you have any questions or comments, feel free to get in touch.