Parsing¶
Let’s have a look at the JSON response from Tileserver.
[
{
"tilejson": "2.0.0",
"name": "Basic preview",
"attribution": "<a href=\"http://openmaptiles.org/\" target=\"_blank\">© OpenMapTiles</a> <a href=\"http://www.openstreetmap.org/about/\" target=\"_blank\">© OpenStreetMap contributors</a>",
"minzoom": 0,
"maxzoom": 20,
"bounds": [8.275, 47.225, 8.8, 47.533],
"format": "png",
"type": "baselayer",
"tiles": ["http://localhost:8081/styles/basic-preview/{z}/{x}/{y}.png"],
"center": [8.537500000000001, 47.379000000000005, 11]
},
{
"tiles": ["http://localhost:8081/data/v3/{z}/{x}/{y}.pbf"],
"name": "OpenMapTiles",
"format": "pbf",
"basename": "zurich_switzerland.mbtiles",
"id": "openmaptiles",
"attribution": "<a href=\"http://openmaptiles.org/\" target=\"_blank\">© OpenMapTiles</a> <a href=\"http://www.openstreetmap.org/about/\" target=\"_blank\">© OpenStreetMap contributors</a>",
"description": "https://openmaptiles.org",
"minzoom": 0,
"maxzoom": 14,
"center": [8.5375, 47.379, 10],
"bounds": [8.275, 47.225, 8.8, 47.533],
"version": "3.3",
"type": "overlay",
"tilejson": "2.0.0"
}
]
The first layer is an XYZ (see tiles
template) PNG (format = 'png'
) layer that is intended as base map imagery (type = 'baselayer'
). OpenSphere already supports XYZ layers and base map layers, so we can take advantage of a lot of code that already exists.
The second layer is a vector format, which we will ignore in this guide. The first JSON object is very similar to the layer config JSON needed to create XYZ layers. So all we have to do is translate it.
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 | goog.declareModuleId('plugin.tileserver.Tileserver');
import ConfigDescriptor from 'opensphere/src/os/data/configdescriptor.js';
import DataManager from 'opensphere/src/os/data/datamanager.js';
import {filterFalsey} from 'opensphere/src/os/fn/fn.js';
import {MAX_ZOOM, MIN_ZOOM} from 'opensphere/src/os/map/map.js';
import Request from 'opensphere/src/os/net/request.js';
import {EPSG3857, EPSG4326} from 'opensphere/src/os/proj/proj.js';
import BaseProvider from 'opensphere/src/os/ui/data/baseprovider.js';
import DescriptorNode from 'opensphere/src/os/ui/data/descriptornode.js';
import {createIconSet} from 'opensphere/src/os/ui/icons/index.js';
import IconsSVG from 'opensphere/src/os/ui/iconssvg.js';
import AbstractLoadingServer from 'opensphere/src/os/ui/server/abstractloadingserver.js';
import * as basemap from 'opensphere/src/plugin/basemap/basemap.js';
import {ID} from './index.js';
const {default: IDataProvider} = goog.requireType('os.data.IDataProvider');
/**
* The Tileserver provider
* @implements {IDataProvider}
*/
export default class Tileserver extends AbstractLoadingServer {
/**
* Constructor.
*/
constructor() {
super();
this.providerType = ID;
}
/**
* @inheritDoc
*/
load(opt_ping) {
super.load(opt_ping);
// clear out any children we already have
this.setChildren(null);
// load the JSON
new Request(this.getUrl()).getPromise().
then(this.onLoad, this.onError, this).
thenCatch(this.onError, this);
}
/**
* @param {string} response
* @protected
*/
onLoad(response) {
let layers;
try {
layers = JSON.parse(response);
} catch (e) {
this.onError('Malformed JSON');
return;
}
if (!Array.isArray(layers)) {
// not sure what we got but it isn't an array of layers
this.onError('Expected an array of layers but got something else');
return;
}
var children = /** @type {Array<!os.structs.ITreeNode>} */ (
layers.map(this.toChildNode, this).filter(filterFalsey));
this.setChildren(children);
this.finish();
}
/**
* @param {Object<string, *>} layer The layer JSON
* @return {?DescriptorNode} The child node for the provider
* @protected
*/
toChildNode(layer) {
if (!layer['tilejson']) {
return null;
}
if (!/^(png|jpe?g|gif)$/i.test(layer['format'])) {
// not our format
return null;
}
var id = this.getId() + BaseProvider.ID_DELIMITER + layer['name'];
var config = {
'type': 'XYZ',
'id': id,
'title': layer['name'],
'urls': layer['tiles'],
'extent': layer['bounds'],
'extentProjection': EPSG4326,
'icons': createIconSet(id, [IconsSVG.TILES], [], [255, 255, 255, 1]),
'projection': EPSG3857,
'minZoom': Math.max(MIN_ZOOM, layer['minzoom']),
'maxZoom': Math.min(MAX_ZOOM, layer['maxzoom']),
'attributions': [layer['attribution']],
'provider': this.getLabel(),
// this delays enabling the descriptor on startup until this provider marks it as ready
'delayUpdateActive': true
};
if (layer['type'] === 'baselayer') {
config['baseType'] = config['type'];
config['type'] = basemap.ID;
config['layerType'] = basemap.LAYER_TYPE;
config['noClear'] = true;
}
var descriptor = /** @type {ConfigDescriptor} */ (DataManager.getInstance().getDescriptor(id));
if (!descriptor) {
descriptor = new ConfigDescriptor();
}
descriptor.setBaseConfig(config);
// add the descriptor to the data manager
DataManager.getInstance().addDescriptor(descriptor);
// mark the descriptor as ready if the user had it enabled previously
descriptor.updateActiveFromTemp();
var node = new DescriptorNode();
node.setDescriptor(descriptor);
return node;
}
/**
* @param {*} e
* @protected
*/
onError(e) {
var msg = Array.isArray(e) ? e.join(' ') : e.toString();
this.setErrorMessage(msg);
}
}
|
Let’s test it.
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 | goog.require('goog.Promise');
goog.require('os.data.ConfigDescriptor');
goog.require('os.net.Request');
goog.require('os.ui.data.BaseProvider');
goog.require('plugin.tileserver');
goog.require('plugin.tileserver.Tileserver');
describe('plugin.tileserver.Tileserver', function() {
const Promise = goog.module.get('goog.Promise');
const {default: ConfigDescriptor} = goog.module.get('os.data.ConfigDescriptor');
const {default: Request} = goog.module.get('os.net.Request');
const {default: BaseProvider} = goog.module.get('os.ui.data.BaseProvider');
const {ID} = goog.module.get('plugin.tileserver');
const {default: Tileserver} = goog.module.get('plugin.tileserver.Tileserver');
it('should configure properly', function() {
var p = new Tileserver();
var conf = {
type: ID,
label: 'Test Server',
url: 'http://localhost/doesnotexist.json'
};
p.configure(conf);
expect(p.getLabel()).toBe(conf.label);
expect(p.getUrl()).toBe(conf.url);
});
it('should load valid JSON', function() {
var p = new Tileserver();
p.setUrl('/something');
// we're going to spy on the getPromise method and return a promise resolving
// to valid JSON
spyOn(Request.prototype, 'getPromise').andReturn(Promise.resolve('[]'));
spyOn(p, 'onLoad').andCallThrough();
spyOn(p, 'onError').andCallThrough();
runs(function() {
p.load();
});
waitsFor(function() {
return p.onLoad.calls.length;
});
runs(function() {
expect(p.onLoad).toHaveBeenCalled();
expect(p.onError).not.toHaveBeenCalled();
});
});
it('should error on invalid JSON', function() {
var p = new Tileserver();
p.setUrl('/something');
// we're going to spy on the getPromise method and return a promise resolving
// to invalid JSON
spyOn(Request.prototype, 'getPromise').andReturn(Promise.resolve('[wut'));
spyOn(p, 'onLoad').andCallThrough();
spyOn(p, 'onError').andCallThrough();
runs(function() {
p.load();
});
waitsFor(function() {
return p.onLoad.calls.length;
});
runs(function() {
expect(p.onLoad).toHaveBeenCalled();
expect(p.onError).toHaveBeenCalled();
});
});
it('should error on request error', function() {
var p = new Tileserver();
p.setUrl('/something');
// we're going to spy on the getPromise method and return a promise rejecting
// with errors
spyOn(Request.prototype, 'getPromise').andReturn(
// request rejects with arrays of all errors that occurred
Promise.reject(['something awful happend']));
spyOn(p, 'onLoad').andCallThrough();
spyOn(p, 'onError').andCallThrough();
runs(function() {
p.load();
});
waitsFor(function() {
return p.onError.calls.length;
});
runs(function() {
expect(p.onLoad).not.toHaveBeenCalled();
expect(p.onError).toHaveBeenCalled();
});
});
it('should ignore JSON that is not an array', function() {
var p = new Tileserver();
p.setUrl('/something');
// we're going to spy on the getPromise method and return a promise resolving
// to valid JSON
spyOn(Request.prototype, 'getPromise').andReturn(Promise.resolve('{}'));
spyOn(p, 'onLoad').andCallThrough();
spyOn(p, 'onError').andCallThrough();
runs(function() {
p.load();
});
waitsFor(function() {
return p.onLoad.calls.length;
});
runs(function() {
expect(p.onLoad).toHaveBeenCalled();
expect(p.onError).toHaveBeenCalled();
});
});
it('should parse Tileserver JSON', function() {
var p = new Tileserver();
p.setUrl('/something');
// we're going to spy on the getPromise method and return a promise resolving to some Tileserver JSON
spyOn(Request.prototype, 'getPromise').andReturn(Promise.resolve(JSON.stringify(
[{
tilejson: '2.0.0',
name: 'Klokantech Basic',
attribution: 'This is a test',
minzoom: 0,
maxzoom: 20,
bounds: [8.275, 47.225, 8.8, 47.533],
format: 'png',
type: 'baselayer',
tiles: ['http://localhost:8081/styles/klokantech-basic/{z}/{x}/{y}.png'],
center: [8.537500000000001, 47.379000000000005, 11]
}, {
tilejson: '2.0.0',
name: 'Klokantech Basic 2',
attribution: 'This is a test',
minzoom: 0,
maxzoom: 20,
bounds: [8.275, 47.225, 8.8, 47.533],
format: 'png',
tiles: ['http://localhost:8081/styles/klokantech-basic/{z}/{x}/{y}.png'],
center: [8.537500000000001, 47.379000000000005, 11]
}, {
tilejson: '2.0.0',
format: 'pbf'
}, {
something: true
}]
)));
spyOn(p, 'onLoad').andCallThrough();
spyOn(p, 'onError').andCallThrough();
// add a config descriptor to the datamanager so that we can test updating on one of the layers
var id = p.getId() + BaseProvider.ID_DELIMITER + 'Klokantech Basic';
var descriptor = new ConfigDescriptor();
descriptor.setBaseConfig({
id: id
});
os.dataManager.addDescriptor(descriptor);
runs(function() {
p.load();
});
waitsFor(function() {
return p.onLoad.calls.length;
});
runs(function() {
expect(p.onLoad).toHaveBeenCalled();
expect(p.onError).not.toHaveBeenCalled();
expect(p.getChildren().length).toBe(2);
expect(p.getChildren()[0].getLabel()).toBe('Klokantech Basic');
expect(p.getChildren()[1].getLabel()).toBe('Klokantech Basic 2');
});
});
});
|
yarn test
should result in a clean test run. Now let’s ensure that our descriptor type is registered in our plugin.
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 | goog.declareModuleId('plugin.tileserver.TileserverPlugin');
import ConfigDescriptor from 'opensphere/src/os/data/configdescriptor.js';
import DataManager from 'opensphere/src/os/data/datamanager.js';
import ProviderEntry from 'opensphere/src/os/data/providerentry.js';
import AbstractPlugin from 'opensphere/src/os/plugin/abstractplugin.js';
import PluginManager from 'opensphere/src/os/plugin/pluginmanager.js';
import Tileserver from './tileserver.js';
import {ID} from './index.js';
/**
* Provides Tileserver support
*/
export default class TileserverPlugin extends AbstractPlugin {
/**
* Constructor.
*/
constructor() {
super();
this.id = ID;
this.errorMessage = null;
}
/**
* @inheritDoc
*/
init() {
const dm = DataManager.getInstance();
dm.registerProviderType(new ProviderEntry(
ID, // the type
Tileserver, // the class
'Tileserver', // the title
'Tileserver layers' // the description
));
dm.registerDescriptorType(ID, ConfigDescriptor);
}
}
// add the plugin to the application
PluginManager.getInstance().addPlugin(new TileserverPlugin());
|
Since ConfigDescriptor
is highly resuable, it is possible that several plugins make that same registration. That’s fine.
Now run the build and open up the debug instance again. This time the server should complete its loading and show a child node for the parsed layer. Toggling the child should enable the given layer, and the layer should persist on refresh.
We’ve got the provider working if added by an admin in config, but what about the user? Let’s handle that next.