Skip to content

Commit

Permalink
add styleimageneeded event for on-demand images
Browse files Browse the repository at this point in the history
The event gets fired when a layer needs an image that the map doesn't
have. The developer has a chance to listen for this event and add an
image within the callback in order to have it included.

This event can be used to dynamically generate icons based on feature
properties.

fix #7587
  • Loading branch information
ansis committed Mar 4, 2019
1 parent a2dc230 commit 3395c5f
Show file tree
Hide file tree
Showing 6 changed files with 133 additions and 1 deletion.
81 changes: 81 additions & 0 deletions docs/pages/example/add-image-missing-generated.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<div id='map'></div>

<script>

var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9'
});

map.on('styleimageneeded', function(e) {
var id = e.id; // id of the missing image

// check if this missing icon is one this function can generate
var prefix = 'square-rgb-';
if (id.indexOf(prefix) !== 0) return;

// extract the color from the id
var rgb = id.replace(prefix, '').split(',').map(Number);

var width = 64; // The image will be 64 pixels square
var bytesPerPixel = 4; // Each pixel is represented by 4 bytes: red, green, blue, and alpha.
var data = new Uint8Array(width * width * bytesPerPixel);

for (var x = 0; x < width; x++) {
for (var y = 0; y < width; y++) {
var offset = (y * width + x) * bytesPerPixel;
data[offset + 0] = rgb[0]; // red
data[offset + 1] = rgb[1]; // green
data[offset + 2] = rgb[2]; // blue
data[offset + 3] = 255; // alpha
}
}

map.addImage(id, {width: width, height: width, data: data});
});

map.on('load', function () {
map.addLayer({
"id": "points",
"type": "symbol",
"source": {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [0, 0]
},
"properties": {
"color": "255,0,0"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [50, 0]
},
"properties": {
"color": "255,209,28"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-50, 0]
},
"properties": {
"color": "242,127,32"
}
}]
}
},
"layout": {
"icon-image": ["concat", "square-rgb-", ["get", "color"]]
}
});
});

</script>
11 changes: 11 additions & 0 deletions docs/pages/example/add-image-missing-generated.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*---
title: Generate and add a missing icon to the map
description: Add a missing icon to the map that was generated at runtime.
tags:
- styles
- layers
pathname: /mapbox-gl-js/example/add-image-missing-generated/
---*/
import Example from '../../components/example';
import html from './add-image-missing-generated.html';
export default Example(html);
7 changes: 6 additions & 1 deletion src/render/image_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import potpack from 'potpack';

import { Event, Evented } from '../util/evented';
import { RGBAImage } from '../util/image';
import { ImagePosition } from './image_atlas';
import Texture from './texture';
Expand Down Expand Up @@ -33,7 +34,7 @@ const padding = 1;
data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time
to refactor this.
*/
class ImageManager {
class ImageManager extends Evented {
images: {[string]: StyleImage};
loaded: boolean;
requestors: Array<{ids: Array<string>, callback: Callback<{[string]: StyleImage}>}>;
Expand All @@ -44,6 +45,7 @@ class ImageManager {
dirty: boolean;

constructor() {
super();
this.images = {};
this.loaded = false;
this.requestors = [];
Expand Down Expand Up @@ -115,6 +117,9 @@ class ImageManager {
const response = {};

for (const id of ids) {
if (!this.images[id]) {
this.fire(new Event('styleimageneeded', { id }));
}
const image = this.images[id];
if (image) {
// Clone the image so that our own copy of its ArrayBuffer doesn't get transferred.
Expand Down
1 change: 1 addition & 0 deletions src/style/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ class Style extends Evented {
this.map = map;
this.dispatcher = new Dispatcher(getWorkerPool(), this);
this.imageManager = new ImageManager();
this.imageManager.setEventedParent(this);
this.glyphManager = new GlyphManager(map._transformRequest, options.localIdeographFontFamily);
this.lineAtlas = new LineAtlas(256, 512);
this.crossTileSymbolIndex = new CrossTileSymbolIndex();
Expand Down
14 changes: 14 additions & 0 deletions src/ui/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,20 @@ export type MapEvent =
*/
| 'sourcedataloading'

/**
* Fired when an icon or pattern needed by the style is missing. The missing image can
* be added with {@link Map#addImage} within this callback to prevent the image from
* being skipped. This event can be used to dynamically generate icons and patterns.
*
* @event styleimageneeded
* @memberof Map
* @instance
* @property {string} id The id of the missing image.
*
* @see [Generate and add a missing icon to the map](https://mapbox.com/mapbox-gl-js/example/add-image-missing-generated/)
*/
| 'styleimageneeded'

/**
* @event style.load
* @memberof Map
Expand Down
20 changes: 20 additions & 0 deletions test/unit/ui/map.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1945,6 +1945,26 @@ test('Map', (t) => {
t.end();
});

t.test('map fires `styleimageneeded` for missing icons', (t) => {
const map = createMap(t);

const id = "missing-image";

let called;
map.on('styleimageneeded', e => {
map.addImage(e.id, {width: 1, height: 1, data: new Uint8Array(4)});
called = e.id;
});

t.notok(map.hasImage(id));

map.style.imageManager.getImages([id], () => {
t.equals(called, id);
t.ok(map.hasImage(id));
t.end();
});
});

t.end();
});

Expand Down

0 comments on commit 3395c5f

Please sign in to comment.