@superrouteca/smap 1.0.2 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/smap.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  /* Generated by js/build.mjs from js/src (see SOURCE.json). Do not edit. */
2
- /*! sMap Web SDK 1.0.2. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
2
+ /*! sMap Web SDK 1.0.6. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
3
3
 
4
4
  var smapCore = null;
5
5
  function smapCreateEngine() {
6
+ var SMAP_BASE_URL = (typeof document !== 'undefined' && document.baseURI) || (typeof location !== 'undefined' && location.href) || 'about:blank';
6
7
  var smapEngineExports = (() => {
7
8
  var __defProp = Object.defineProperty;
8
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -4598,7 +4599,7 @@ Use an identity property function instead: \`{ "type": "identity", "property": $
4598
4599
  }
4599
4600
  }
4600
4601
  function el() {
4601
- let e66 = "";
4602
+ let e66 = SMAP_BASE_URL;
4602
4603
  if (!/^https?:/.test(e66)) return ``;
4603
4604
  let t2 = e66.endsWith(`-dev.mjs`) ? `maplibre-gl-worker-dev.mjs` : `maplibre-gl-worker.mjs`, n2 = new URL(`./${t2}`, e66);
4604
4605
  return n2.searchParams.set(`v`, l), n2.href;
@@ -4621,7 +4622,7 @@ Use an identity property function instead: \`{ "type": "identity", "property": $
4621
4622
  return URL.createObjectURL(r2);
4622
4623
  }
4623
4624
  function il(e66) {
4624
- let t2 = new Blob([`import ${JSON.stringify(new URL(e66, "").href)}`], { type: `text/javascript` });
4625
+ let t2 = new Blob([`import ${JSON.stringify(new URL(e66, SMAP_BASE_URL).href)}`], { type: `text/javascript` });
4625
4626
  return URL.createObjectURL(t2);
4626
4627
  }
4627
4628
  async function al() {
@@ -26864,14 +26865,14 @@ function smapCreateSdk(engine) {
26864
26865
  */
26865
26866
  (function (root, factory) {
26866
26867
  if (typeof module === 'object' && module.exports) {
26867
- module.exports = factory(root.maplibregl || require('maplibre-gl'));
26868
+ module.exports = factory(root.maplibregl !== undefined ? root.maplibregl : require('maplibre-gl'));
26868
26869
  } else {
26869
26870
  root.sMap = factory(root.maplibregl);
26870
26871
  }
26871
26872
  })(typeof self !== 'undefined' ? self : this, function (engine) {
26872
26873
  'use strict';
26873
26874
 
26874
- var VERSION = '1.0.2';
26875
+ var VERSION = '1.0.6';
26875
26876
  var FLAVORS = ['light', 'white', 'grayscale', 'dark', 'black'];
26876
26877
  var BASEMAP_SOURCE = 'basemap';
26877
26878
  var BUILDINGS_LAYER = 'smap-buildings-3d';
@@ -26970,6 +26971,230 @@ function smapCreateSdk(engine) {
26970
26971
  };
26971
26972
  }
26972
26973
 
26974
+ // ------------------------------------------------------------------ popups
26975
+
26976
+ var POPUP_OPTIONS = ['className', 'maxWidth', 'minWidth', 'offset', 'anchor', 'closeButton', 'closeOnClick', 'focusAfterOpen', 'autoPan'];
26977
+ // Shown while a popup's content is on its way: three pulsing dots, no text.
26978
+ var POPUP_LOADING = '<div class="smap-popup-loading" role="status"><span></span><span></span><span></span></div>';
26979
+ var HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
26980
+
26981
+ function escapeHtml(value) {
26982
+ return String(value).replace(/[&<>"']/g, function (c) { return HTML_ESCAPES[c]; });
26983
+ }
26984
+
26985
+ /**
26986
+ * A popup function from a template: every {name} is replaced by the feature's property of that name, HTML-escaped
26987
+ * (empty when the feature has none). The template itself is trusted HTML. Compiled once; nothing runs until a click.
26988
+ * popupTemplate('<b>{name}</b><br>{address}')
26989
+ */
26990
+ function popupTemplate(template) {
26991
+ // Even entries are the template's own text, odd entries property names.
26992
+ var parts = String(template).split(/\{([^{}]+)\}/);
26993
+ for (var i = 1; i < parts.length; i += 2) { parts[i] = parts[i].trim(); }
26994
+ return function (properties) {
26995
+ var out = parts[0];
26996
+ for (var j = 1; j < parts.length; j += 2) {
26997
+ var v = properties ? properties[parts[j]] : undefined;
26998
+ out += (v === undefined || v === null ? '' : escapeHtml(v)) + parts[j + 1];
26999
+ }
27000
+ return out;
27001
+ };
27002
+ }
27003
+
27004
+ function isThenable(v) { return !!v && (typeof v === 'object' || typeof v === 'function') && typeof v.then === 'function'; }
27005
+
27006
+ function cssSize(v) { return typeof v === 'number' ? v + 'px' : v; }
27007
+
27008
+ // ------------------------------------------------------------------ drawn images (pins, numbers, badges, arrows)
27009
+
27010
+ // A style value: a constant, {property: 'name'} (the feature's property, `default` when it has none), or an engine
27011
+ // expression (an array).
27012
+ function valueExpr(v, fallback) {
27013
+ if (v === undefined || v === null) { return fallback; }
27014
+ if (Array.isArray(v)) { return v; }
27015
+ if (typeof v === 'object' && v.property) {
27016
+ return v['default'] !== undefined ? ['coalesce', ['get', v.property], v['default']] : ['get', v.property];
27017
+ }
27018
+ return v;
27019
+ }
27020
+
27021
+ // Image ids carry what the image shows; the map draws each one the first time a feature needs it (see _drawImage).
27022
+ var IMAGE_PREFIX = 'smap-img|';
27023
+ var SQRT1_2 = Math.SQRT1_2;
27024
+
27025
+ // The pin of Superroute's route map: a square with three rounded corners turned 45 degrees, its sharp corner the tip.
27026
+ // tipToHead: from the position up to the centre of the round part (where the number goes); badge: the badge's centre
27027
+ // from the position (right of the round part, as the page's badge sits on the turned pin's corner).
27028
+ function markerGeometry(shape, size) {
27029
+ var k = size / 32;
27030
+ if (shape === 'circle' || shape === 'vehicle') {
27031
+ return { k: k, tipToHead: 0, badge: [size * 0.36, -size * 0.36] };
27032
+ }
27033
+ var half = size * SQRT1_2; // the centre of the round part, above the tip
27034
+ return { k: k, tipToHead: half, badge: [14.1 * k, -half] };
27035
+ }
27036
+
27037
+ // A rounded rectangle path whose corners are ellipses: radii [[rx, ry] top-left, top-right, bottom-right, bottom-left].
27038
+ function roundedPath(ctx, x, y, w, h, r) {
27039
+ ctx.beginPath();
27040
+ ctx.moveTo(x + r[0][0], y);
27041
+ ctx.lineTo(x + w - r[1][0], y);
27042
+ if (r[1][0] && r[1][1]) { ctx.ellipse(x + w - r[1][0], y + r[1][1], r[1][0], r[1][1], 0, -Math.PI / 2, 0); }
27043
+ ctx.lineTo(x + w, y + h - r[2][1]);
27044
+ if (r[2][0] && r[2][1]) { ctx.ellipse(x + w - r[2][0], y + h - r[2][1], r[2][0], r[2][1], 0, 0, Math.PI / 2); }
27045
+ ctx.lineTo(x + r[3][0], y + h);
27046
+ if (r[3][0] && r[3][1]) { ctx.ellipse(x + r[3][0], y + h - r[3][1], r[3][0], r[3][1], 0, Math.PI / 2, Math.PI); }
27047
+ ctx.lineTo(x, y + r[0][1]);
27048
+ if (r[0][0] && r[0][1]) { ctx.ellipse(x + r[0][0], y + r[0][1], r[0][0], r[0][1], 0, Math.PI, Math.PI * 1.5); }
27049
+ ctx.closePath();
27050
+ }
27051
+
27052
+ var PIN_PAD = 6; // room for the shadow around a pin, in pixels
27053
+
27054
+ // Each draw function gets a 2D context already scaled to the pixel ratio and returns nothing; sizes are in pixels.
27055
+ var IMAGE_KINDS = {
27056
+ // pin|shape|fill|border|borderWidth|size (shape pin, circle, or vehicle: the route map's live position, a white
27057
+ // circle with a truck in the border colour)
27058
+ pin: function (args) {
27059
+ var shape = args[0], fill = args[1], border = args[2], bw = Number(args[3]), size = Number(args[4]);
27060
+ var g = markerGeometry(shape, size);
27061
+ var reach = shape === 'pin' ? g.tipToHead : size / 2; // farthest the shape goes from its centre
27062
+ var w = Math.ceil(2 * reach + 2 * PIN_PAD), h = w;
27063
+ return {
27064
+ width: w, height: h,
27065
+ draw: function (ctx, ratio) {
27066
+ var c = w / 2;
27067
+ if (shape === 'vehicle') { drawVehicle(ctx, ratio, c, size, border); return; }
27068
+ ctx.save();
27069
+ ctx.translate(c, c);
27070
+ var s = size / 2;
27071
+ var outer, inner;
27072
+ if (shape === 'circle') {
27073
+ outer = function () { ctx.beginPath(); ctx.arc(0, 0, s, 0, Math.PI * 2); };
27074
+ inner = function () { ctx.beginPath(); ctx.arc(0, 0, Math.max(0, s - bw), 0, Math.PI * 2); };
27075
+ ctx.shadowOffsetY = 3 * ratio;
27076
+ } else {
27077
+ ctx.rotate(Math.PI / 4);
27078
+ outer = function () { roundedPath(ctx, -s, -s, size, size, [[s, s], [s, size], [0, 0], [size, s]]); };
27079
+ var t = Math.max(0, s - bw), r2 = Math.max(0, size - bw);
27080
+ inner = function () { roundedPath(ctx, -s + bw, -s + bw, size - 2 * bw, size - 2 * bw, [[t, t], [t, r2], [0, 0], [r2, t]]); };
27081
+ // The page's box-shadow (0 3px) turns with the pin.
27082
+ ctx.shadowOffsetX = -3 * SQRT1_2 * ratio;
27083
+ ctx.shadowOffsetY = 3 * SQRT1_2 * ratio;
27084
+ }
27085
+ ctx.shadowColor = 'rgba(0,0,0,0.3)';
27086
+ ctx.shadowBlur = 8 * ratio;
27087
+ outer();
27088
+ ctx.fillStyle = border;
27089
+ ctx.fill();
27090
+ ctx.shadowColor = 'transparent';
27091
+ inner();
27092
+ ctx.fillStyle = fill;
27093
+ ctx.fill();
27094
+ ctx.restore();
27095
+ },
27096
+ };
27097
+ },
27098
+ // pinnum|shape|fill|border|borderWidth|size|textColor|text: a pin with its number drawn in, so a pin above covers a
27099
+ // pin below completely (used close up, where few pins are in view; further out the number is its own layer).
27100
+ pinnum: function (args, measure) {
27101
+ var pin = IMAGE_KINDS.pin(args.slice(0, 5));
27102
+ var size = Number(args[4]), color = args[5], text = args.slice(6).join('|');
27103
+ var px = 14 * size / 32, font = 'bold ' + px + 'px monospace';
27104
+ return {
27105
+ width: pin.width, height: pin.height,
27106
+ draw: function (ctx, ratio) {
27107
+ pin.draw(ctx, ratio);
27108
+ if (text === '') { return; }
27109
+ ctx.save();
27110
+ ctx.font = font;
27111
+ ctx.textAlign = 'center';
27112
+ ctx.textBaseline = 'middle';
27113
+ ctx.shadowColor = 'rgba(0,0,0,0.5)';
27114
+ ctx.shadowOffsetX = ratio;
27115
+ ctx.shadowOffsetY = ratio;
27116
+ ctx.shadowBlur = 2 * ratio;
27117
+ ctx.fillStyle = color;
27118
+ ctx.fillText(text, pin.width / 2, pin.height / 2 + 0.5);
27119
+ ctx.restore();
27120
+ },
27121
+ };
27122
+ },
27123
+ // num|color|size|text (bold, with the route map's text shadow)
27124
+ num: function (args, measure) {
27125
+ var color = args[0], size = Number(args[1]), text = args.slice(2).join('|');
27126
+ var px = 14 * size / 32;
27127
+ var font = 'bold ' + px + 'px monospace';
27128
+ var w = Math.ceil(measure(font, text) + 6), h = Math.ceil(px * 1.4 + 4);
27129
+ return {
27130
+ width: w, height: h,
27131
+ draw: function (ctx, ratio) {
27132
+ ctx.font = font;
27133
+ ctx.textAlign = 'center';
27134
+ ctx.textBaseline = 'middle';
27135
+ ctx.shadowColor = 'rgba(0,0,0,0.5)';
27136
+ ctx.shadowOffsetX = ratio;
27137
+ ctx.shadowOffsetY = ratio;
27138
+ ctx.shadowBlur = 2 * ratio;
27139
+ ctx.fillStyle = color;
27140
+ ctx.fillText(text, w / 2, h / 2);
27141
+ },
27142
+ };
27143
+ },
27144
+ // badge|text (red circle, white border, at least 18 px inside the border)
27145
+ badge: function (args, measure) {
27146
+ var text = args.join('|');
27147
+ var font = 'bold 10px sans-serif';
27148
+ var inner = Math.max(18, Math.ceil(measure(font, text) + 4));
27149
+ var w = inner + 4 + 6, h = 18 + 4 + 6;
27150
+ return {
27151
+ width: w, height: h,
27152
+ draw: function (ctx, ratio) {
27153
+ var bw = inner + 4, bh = 22, x = 3, y = 2;
27154
+ var r = bh / 2;
27155
+ ctx.shadowColor = 'rgba(0,0,0,0.4)';
27156
+ ctx.shadowOffsetY = 2 * ratio;
27157
+ ctx.shadowBlur = 4 * ratio;
27158
+ roundedPath(ctx, x, y, bw, bh, [[r, r], [r, r], [r, r], [r, r]]);
27159
+ ctx.fillStyle = '#ffffff';
27160
+ ctx.fill();
27161
+ ctx.shadowColor = 'transparent';
27162
+ roundedPath(ctx, x + 2, y + 2, bw - 4, bh - 4, [[r - 2, r - 2], [r - 2, r - 2], [r - 2, r - 2], [r - 2, r - 2]]);
27163
+ ctx.fillStyle = '#e74c3c';
27164
+ ctx.fill();
27165
+ ctx.font = font;
27166
+ ctx.textAlign = 'center';
27167
+ ctx.textBaseline = 'middle';
27168
+ ctx.fillStyle = '#ffffff';
27169
+ ctx.fillText(text, x + bw / 2, y + bh / 2 + 0.5);
27170
+ },
27171
+ };
27172
+ },
27173
+ // arrow|size|color (an open arrowhead pointing along the line, like the route map's)
27174
+ arrow: function (args) {
27175
+ var size = Number(args[0]), color = args.slice(1).join('|');
27176
+ var w = Math.ceil(size + 4), h = w;
27177
+ return {
27178
+ width: w, height: h,
27179
+ draw: function (ctx) {
27180
+ var len = size, back = len * Math.cos(Math.PI / 6), half = len * Math.sin(Math.PI / 6);
27181
+ var tipX = w / 2 + back / 2, cy = h / 2;
27182
+ ctx.strokeStyle = color;
27183
+ ctx.lineWidth = 2;
27184
+ ctx.lineCap = 'round';
27185
+ ctx.lineJoin = 'round';
27186
+ ctx.beginPath();
27187
+ ctx.moveTo(tipX - back, cy - half);
27188
+ ctx.lineTo(tipX, cy);
27189
+ ctx.lineTo(tipX - back, cy + half);
27190
+ ctx.stroke();
27191
+ },
27192
+ };
27193
+ },
27194
+ };
27195
+
27196
+ function drawnImageId(kind, parts) { return ['concat', IMAGE_PREFIX + kind].concat(parts.reduce(function (a, p) { return a.concat(['|', p]); }, [])); }
27197
+
26973
27198
  var NODE_TTL = 3600 * 1000;
26974
27199
 
26975
27200
  function timed(url, ms) {
@@ -27050,6 +27275,9 @@ function smapCreateSdk(engine) {
27050
27275
  * @param {boolean} [options.nearest=true] read from the nearest sMap node (asked of baseUrl, remembered for an hour)
27051
27276
  * @param {string[]} [options.nodes] node URLs known in advance, used while baseUrl is down
27052
27277
  * @param {'mercator'|'globe'} [options.projection]
27278
+ * @param {Object} [options.popup] default popup options of every layer and openPopup (className, maxWidth,
27279
+ * minWidth, offset, anchor, closeButton, closeOnClick, focusAfterOpen)
27280
+ * @param {string|Node} [options.popupLoading] shown while a popup's content is a pending promise (default: dots)
27053
27281
  * Every other option (center, zoom, pitch, bearing, minZoom, maxZoom, maxBounds, hash, …) goes to the engine.
27054
27282
  */
27055
27283
  function SMap(options) {
@@ -27069,6 +27297,12 @@ function smapCreateSdk(engine) {
27069
27297
  this._buildings = false;
27070
27298
  this._handlers = {};
27071
27299
  this._refreshTimer = null;
27300
+ this._popupDefaults = options.popup || {};
27301
+ this._popupLoading = options.popupLoading;
27302
+ this._autoZoom = options.autoZoom !== false;
27303
+ this._wasd = options.keyboard3D;
27304
+ this._popup = null;
27305
+ this._popupSeq = 0;
27072
27306
  // True between a style's load and the next style change. The engine's own isStyleLoaded() turns false while any
27073
27307
  // source is loading data, which would leave layers added meanwhile waiting for a load that never comes.
27074
27308
  this._styleReady = false;
@@ -27076,7 +27310,7 @@ function smapCreateSdk(engine) {
27076
27310
  var self = this;
27077
27311
  var engineOptions = {};
27078
27312
  for (var k in options) {
27079
- if (Object.prototype.hasOwnProperty.call(options, k) && ['token', 'getToken', 'apiKey', 'style', 'language', 'baseUrl', 'projection', 'nearest', 'nodes'].indexOf(k) < 0) {
27313
+ if (Object.prototype.hasOwnProperty.call(options, k) && ['token', 'getToken', 'apiKey', 'style', 'language', 'baseUrl', 'projection', 'nearest', 'nodes', 'popup', 'popupLoading', 'autoZoom', 'keyboard3D'].indexOf(k) < 0) {
27080
27314
  engineOptions[k] = options[k];
27081
27315
  }
27082
27316
  }
@@ -27109,6 +27343,14 @@ function smapCreateSdk(engine) {
27109
27343
  badge._place();
27110
27344
  }
27111
27345
  self.engine.on('style.load', function () { self._styleReady = true; self._restore(); });
27346
+ self._keyboard3D();
27347
+ // One click handler for every layer's popup: the engine's hit test over those layers, the top feature opens.
27348
+ self.engine.on('click', function (e) { self._popupClick(e); });
27349
+ self._styleClass();
27350
+ // Pins, numbers, badges and arrows are drawn the first time a feature needs one (and again after a style change).
27351
+ if (self.engine.setMissingStyleImageResolver) {
27352
+ self.engine.setMissingStyleImageResolver(function (id) { self._drawImage(id); });
27353
+ }
27112
27354
  return new Promise(function (resolve) { self.engine.once('load', function () { resolve(self); }); });
27113
27355
  });
27114
27356
  if (this._token && this._getToken) { this._scheduleRefresh(); }
@@ -27144,10 +27386,263 @@ function smapCreateSdk(engine) {
27144
27386
  if (FLAVORS.indexOf(style) >= 0) { this._flavor = style; this._customStyle = null; } else { this._customStyle = style; }
27145
27387
  this._styleReady = false;
27146
27388
  this.engine.setStyle(this._styleUrl());
27389
+ this._styleClass();
27390
+ return this;
27391
+ };
27392
+
27393
+ // The map container carries smap-style-<scheme>, so the stylesheet can follow the scheme (dark popups).
27394
+ SMap.prototype._styleClass = function () {
27395
+ var c = this.engine && this.engine.getContainer && this.engine.getContainer();
27396
+ if (!c || !c.classList) { return; }
27397
+ for (var i = 0; i < FLAVORS.length; i++) { c.classList.remove('smap-style-' + FLAVORS[i]); }
27398
+ if (!this._customStyle) { c.classList.add('smap-style-' + this._flavor); }
27399
+ };
27400
+
27401
+ // Draws an image the SDK named (IMAGE_PREFIX + kind|args) and adds it to the map; other names are left alone.
27402
+ // The live-position marker of the route map: a white circle (85%) with a truck in the driver colour.
27403
+ function drawVehicle(ctx, ratio, c, size, color) {
27404
+ var r = size / 2, k = size / 24;
27405
+ ctx.save();
27406
+ ctx.translate(c, c);
27407
+ ctx.shadowColor = 'rgba(0,0,0,0.5)';
27408
+ ctx.shadowBlur = 2 * ratio;
27409
+ ctx.beginPath(); ctx.arc(0, 0, r, 0, Math.PI * 2);
27410
+ ctx.fillStyle = 'rgba(255,255,255,0.85)'; ctx.fill();
27411
+ ctx.shadowColor = 'transparent';
27412
+ ctx.scale(k, k);
27413
+ ctx.fillStyle = color;
27414
+ // cargo box, cab and two wheels, about 14 x 10 px on a 24 px marker
27415
+ ctx.fillRect(-7, -5, 8.5, 7);
27416
+ roundedPath(ctx, 2.2, -2.6, 4.8, 4.6, [[1.4, 1.4], [0.6, 0.6], [0, 0], [0, 0]]); ctx.fill();
27417
+ ctx.beginPath(); ctx.arc(-4.2, 3.4, 1.9, 0, Math.PI * 2); ctx.arc(4.1, 3.4, 1.9, 0, Math.PI * 2); ctx.fill();
27418
+ ctx.fillStyle = 'rgba(255,255,255,0.85)';
27419
+ ctx.beginPath(); ctx.arc(-4.2, 3.4, 0.7, 0, Math.PI * 2); ctx.arc(4.1, 3.4, 0.7, 0, Math.PI * 2); ctx.fill();
27420
+ ctx.restore();
27421
+ }
27422
+
27423
+ SMap.prototype._drawImage = function (id) {
27424
+ if (typeof id !== 'string' || id.indexOf(IMAGE_PREFIX) !== 0) { return; }
27425
+ var m = this.engine;
27426
+ if (m.hasImage(id)) { return; }
27427
+ var parts = id.slice(IMAGE_PREFIX.length).split('|');
27428
+ var kind = IMAGE_KINDS[parts[0]];
27429
+ if (!kind) { return; }
27430
+ var doc = m.getContainer().ownerDocument;
27431
+ var win = doc.defaultView || {};
27432
+ var ratio = Math.min(3, Math.max(1, Math.ceil(win.devicePixelRatio || 1)));
27433
+ var canvas = doc.createElement('canvas');
27434
+ var ctx = canvas.getContext('2d');
27435
+ var measure = function (font, text) { ctx.font = font; return ctx.measureText(text).width; };
27436
+ var image = kind(parts.slice(1), measure);
27437
+ canvas.width = Math.ceil(image.width * ratio);
27438
+ canvas.height = Math.ceil(image.height * ratio);
27439
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
27440
+ image.draw(ctx, ratio);
27441
+ m.addImage(id, ctx.getImageData(0, 0, canvas.width, canvas.height), { pixelRatio: ratio });
27442
+ this._imagesDrawn = (this._imagesDrawn || 0) + 1;
27443
+ };
27444
+
27445
+ /**
27446
+ * Opens the map's popup at a position, closing the one open before (there is one popup per map).
27447
+ * @param {Array|Object} lngLat [lng, lat] or {lng, lat}
27448
+ * @param {string|Node|Promise} content trusted HTML (inserted as is, never sanitized), a DOM node, or a promise
27449
+ * of either (popupLoading shows meanwhile; a rejection closes the popup
27450
+ * and is reported as the map's 'error' event)
27451
+ * @param {Object} [options] popup options over the map's `popup` defaults, and `loading`
27452
+ */
27453
+ SMap.prototype.openPopup = function (lngLat, content, options) {
27454
+ var self = this;
27455
+ if (!this.engine) { this.ready.then(function () { self.openPopup(lngLat, content, options); }); return this; }
27456
+ this.closePopup();
27457
+ if (!content) { return this; }
27458
+ var seq = ++this._popupSeq;
27459
+ var o = Object.assign({}, this._popupDefaults, options || {});
27460
+ var engineOptions = { offset: 12, className: 'smap-popup' + (o.className ? ' ' + o.className : '') };
27461
+ for (var i = 0; i < POPUP_OPTIONS.length; i++) {
27462
+ var k = POPUP_OPTIONS[i];
27463
+ if (k !== 'className' && k !== 'minWidth' && k !== 'autoPan' && o[k] !== undefined) { engineOptions[k] = k === 'maxWidth' ? cssSize(o[k]) : o[k]; }
27464
+ }
27465
+ var popup = new engine.Popup(engineOptions).setLngLat(lngLat);
27466
+ this._popup = popup;
27467
+ var pending = isThenable(content);
27468
+ var loading = o.loading !== undefined ? o.loading : (this._popupLoading !== undefined ? this._popupLoading : POPUP_LOADING);
27469
+ this._popupContent(popup, pending ? loading : content);
27470
+ popup.addTo(this.engine);
27471
+ var el = popup.getElement && popup.getElement();
27472
+ if (el && o.minWidth !== undefined) { el.style.minWidth = cssSize(o.minWidth); }
27473
+ if (o.autoPan !== false) {
27474
+ // After the engine has placed it (next frame), so its box is final.
27475
+ var raf = (typeof requestAnimationFrame === 'function') ? requestAnimationFrame : function (fn) { return setTimeout(fn, 16); };
27476
+ raf(function () { if (self._popup === popup) { self._panIntoView(popup); } });
27477
+ }
27478
+ if (pending) {
27479
+ content.then(function (answer) {
27480
+ // A later popup, or a close, makes this answer stale.
27481
+ if (seq !== self._popupSeq || self._popup !== popup) { return; }
27482
+ if (answer) { self._popupContent(popup, answer); } else { self.closePopup(); }
27483
+ }, function (error) {
27484
+ if (seq !== self._popupSeq || self._popup !== popup) { return; }
27485
+ self.closePopup();
27486
+ self._reportError(error);
27487
+ });
27488
+ }
27489
+ return this;
27490
+ };
27491
+
27492
+ /** Pans the map so the popup is fully inside it, with a small margin (Leaflet's autoPan). */
27493
+ SMap.prototype._panIntoView = function (popup) {
27494
+ var m = this.engine, el = popup.getElement && popup.getElement();
27495
+ if (!el || !m.getContainer || !m.panBy || !el.getBoundingClientRect) { return; }
27496
+ var box = el.getBoundingClientRect(), frame = m.getContainer().getBoundingClientRect(), pad = 10, dx = 0, dy = 0;
27497
+ if (box.top < frame.top + pad) { dy = box.top - frame.top - pad; } else if (box.bottom > frame.bottom - pad) { dy = box.bottom - frame.bottom + pad; }
27498
+ if (box.left < frame.left + pad) { dx = box.left - frame.left - pad; } else if (box.right > frame.right - pad) { dx = box.right - frame.right + pad; }
27499
+ if (dx || dy) { m.panBy([dx, dy], { duration: 250 }); }
27500
+ };
27501
+
27502
+ /** Closes the map's popup, if one is open. */
27503
+ SMap.prototype.closePopup = function () {
27504
+ var popup = this._popup;
27505
+ this._popup = null;
27506
+ this._popupSeq++;
27507
+ if (popup) { popup.remove(); }
27147
27508
  return this;
27148
27509
  };
27149
27510
 
27511
+ SMap.prototype._popupContent = function (popup, content) {
27512
+ if (typeof content === 'string') { popup.setHTML(content); } else { popup.setDOMContent(content); }
27513
+ };
27514
+
27515
+ SMap.prototype._reportError = function (error) {
27516
+ var m = this.engine;
27517
+ if (m && engine.ErrorEvent && m.fire) { m.fire(new engine.ErrorEvent(error)); } else if (typeof console !== 'undefined') { console.error(error); }
27518
+ };
27519
+
27520
+ // A click on the map: the top feature of the layers with a popup, if any, opens its layer's popup.
27521
+ SMap.prototype._popupClick = function (e) {
27522
+ var m = this.engine;
27523
+ var ids = [];
27524
+ var byEngineLayer = {};
27525
+ for (var i = 0; i < this._order.length; i++) {
27526
+ var def = this._layers[this._order[i]];
27527
+ if (def.o.popup && def.popupLayer && !def.hidden && m.getLayer(def.popupLayer)) {
27528
+ ids.push(def.popupLayer);
27529
+ byEngineLayer[def.popupLayer] = def;
27530
+ if (def.hoverLayer && m.getLayer(def.hoverLayer)) { ids.push(def.hoverLayer); byEngineLayer[def.hoverLayer] = def; }
27531
+ }
27532
+ }
27533
+ if (!ids.length) { return; }
27534
+ var hits = m.queryRenderedFeatures(e.point, { layers: ids });
27535
+ if (!hits || !hits.length) { return; }
27536
+ var f = hits[0];
27537
+ var hit = byEngineLayer[f.layer && f.layer.id];
27538
+ if (!hit) { return; }
27539
+ // A tight pile of pins: zoom in around the click so they come apart, or, when they still overlap close up (or
27540
+ // share one spot), offer a chooser. A layer turns this off with marker.overlap === false.
27541
+ if (this._autoZoom && hit.o.marker && hit.o.marker.overlap !== false && e.point && m.project) {
27542
+ var ov = hit.o.marker.overlap || {}, near = ov.radius || 12, threshold = ov.threshold || 4;
27543
+ var box = [[e.point.x - near, e.point.y - near], [e.point.x + near, e.point.y + near]];
27544
+ var seen = {}, pile = [];
27545
+ (m.queryRenderedFeatures(box, { layers: ids }) || []).forEach(function (x) {
27546
+ var d = byEngineLayer[x.layer && x.layer.id];
27547
+ if (d !== hit || !x.geometry || x.geometry.type !== 'Point') { return; }
27548
+ var key = JSON.stringify(x.geometry.coordinates) + JSON.stringify(x.properties || {});
27549
+ if (!seen[key]) { seen[key] = true; pile.push(x); }
27550
+ });
27551
+ if (pile.length >= 2) {
27552
+ var spots = {};
27553
+ pile.forEach(function (x) { spots[x.geometry.coordinates.map(function (c) { return c.toFixed(6); }).join(',')] = true; });
27554
+ var oneSpot = Object.keys(spots).length === 1;
27555
+ var closeUp = m.getZoom() >= (ov.maxZoom || 17);
27556
+ if (pile.length >= threshold && !oneSpot && !closeUp) {
27557
+ m.easeTo({ center: e.lngLat, zoom: Math.min(m.getZoom() + (ov.zoomBy || 2), ov.maxZoom || 17), duration: 400 });
27558
+ return;
27559
+ }
27560
+ if (pile.length >= threshold || oneSpot) { this._chooser(hit, pile, e.lngLat); return; }
27561
+ }
27562
+ }
27563
+ this._openFeaturePopup(hit, f, e.lngLat);
27564
+ };
27565
+
27566
+ /** A small list of the pins under a click; choosing one opens its popup. */
27567
+ SMap.prototype._chooser = function (hit, pile, lngLat) {
27568
+ var self = this, mk = hit.o.marker, doc = this.engine.getContainer().ownerDocument;
27569
+ var list = doc.createElement('div');
27570
+ list.className = 'smap-chooser';
27571
+ var esc = function (v) { return String(v == null ? '' : v).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); };
27572
+ var plainValue = function (v, p) {
27573
+ if (v && typeof v === 'object' && !Array.isArray(v) && v.property) { return p[v.property] !== undefined ? p[v.property] : v.default; }
27574
+ return Array.isArray(v) ? undefined : v;
27575
+ };
27576
+ pile.slice(0, 50).forEach(function (x, i) {
27577
+ var p = x.properties || {};
27578
+ var label = mk.overlap && typeof mk.overlap.label === 'function' ? mk.overlap.label(p, x) : null;
27579
+ var number = plainValue(mk.text, p), fill = plainValue(mk.fill, p) || '#ffffff', border = plainValue(mk.border, p) || hit.o.color || '#4f46e5';
27580
+ var item = doc.createElement('button');
27581
+ item.type = 'button';
27582
+ item.className = 'smap-chooser-item';
27583
+ item.innerHTML = '<span class="smap-chooser-pin" style="background:' + esc(fill) + ';border-color:' + esc(border) + '">' + esc(number == null ? '' : number) + '</span>'
27584
+ + '<span class="smap-chooser-label">' + esc(label != null ? label : (number != null ? number : i + 1)) + '</span>';
27585
+ item.addEventListener('click', function (ev) { ev.stopPropagation(); self._openFeaturePopup(hit, x, x.geometry.coordinates); });
27586
+ list.appendChild(item);
27587
+ });
27588
+ this._unpin();
27589
+ this.openPopup(lngLat, list, { className: 'smap-chooser-popup', anchor: 'bottom', offset: 12 });
27590
+ };
27591
+
27592
+ /** Opens a feature's own popup (the layer's popup function), above a pin when the layer draws pins. */
27593
+ SMap.prototype._openFeaturePopup = function (hit, f, lngLat) {
27594
+ var m = this.engine;
27595
+ // Points open at their own position; lines and areas where they were clicked.
27596
+ var at = hit.kind === 'points' && f.geometry && f.geometry.type === 'Point' ? f.geometry.coordinates : lngLat;
27597
+ var content;
27598
+ try { content = hit.o.popup(f.properties || {}, f); } catch (error) { this._reportError(error); return; }
27599
+ var popupOptions = Object.assign({}, hit.o.popupOptions || {});
27600
+ if (hit.o.marker && popupOptions.offset === undefined && this._popupDefaults.offset === undefined) {
27601
+ // Just above the pin as it is drawn now (its scale may follow the zoom).
27602
+ var mk = hit.o.marker, size = mk.size || 32, k = scaleAt(mk.scale, m.getZoom ? m.getZoom() : 0);
27603
+ popupOptions.offset = mk.shape === 'circle' || mk.shape === 'vehicle' ? Math.round((size / 2) * k + 4) : Math.round((markerGeometry('pin', size).tipToHead + size / 2) * k + 2);
27604
+ }
27605
+ // Above the pin, always (as on Superroute's route map); the map pans to make room instead of flipping it below.
27606
+ if (hit.o.marker && popupOptions.anchor === undefined && this._popupDefaults.anchor === undefined) { popupOptions.anchor = 'bottom'; }
27607
+ if (hit.o.popupLoading !== undefined) { popupOptions.loading = hit.o.popupLoading; }
27608
+ this._unpin();
27609
+ this.openPopup(at, content, popupOptions);
27610
+ // The clicked pin stays in front while its popup is open (the route map's rule).
27611
+ if (hit.hoverSource && this._popup) {
27612
+ var self = this, popup = this._popup;
27613
+ this._setHover(null, hit, f, 'popup');
27614
+ hit.pinned = popup;
27615
+ this._pinnedDef = hit;
27616
+ if (popup.on) { popup.on('close', function () { if (hit.pinned === popup) { self._unpin(); } }); }
27617
+ }
27618
+ };
27619
+
27150
27620
  /** Switches the label language; your layers are kept. */
27621
+ /**
27622
+ * A marker scale at a zoom: a number, or the linear / step zoom expressions the SDK documents
27623
+ * (['interpolate', ['linear'], ['zoom'], z, v, …], ['step', ['zoom'], v, z, v, …]); anything else counts as 1.
27624
+ */
27625
+ function scaleAt(scale, zoom) {
27626
+ if (scale === undefined || scale === null) { return 1; }
27627
+ if (typeof scale === 'number') { return scale; }
27628
+ if (!Array.isArray(scale)) { return 1; }
27629
+ var isZoom = function (x) { return Array.isArray(x) && x[0] === 'zoom'; };
27630
+ if (scale[0] === 'interpolate' && isZoom(scale[2])) {
27631
+ var stops = scale.slice(3);
27632
+ if (zoom <= stops[0]) { return stops[1]; }
27633
+ for (var i = 2; i < stops.length; i += 2) {
27634
+ if (zoom <= stops[i]) { var t = (zoom - stops[i - 2]) / (stops[i] - stops[i - 2]); return stops[i - 1] + t * (stops[i + 1] - stops[i - 1]); }
27635
+ }
27636
+ return stops[stops.length - 1];
27637
+ }
27638
+ if (scale[0] === 'step' && isZoom(scale[1])) {
27639
+ var value = scale[2];
27640
+ for (var j = 3; j < scale.length; j += 2) { if (zoom >= scale[j]) { value = scale[j + 1]; } }
27641
+ return value;
27642
+ }
27643
+ return 1;
27644
+ }
27645
+
27151
27646
  SMap.prototype.setLanguage = function (language) {
27152
27647
  this._language = language;
27153
27648
  if (!this._customStyle) { this._styleReady = false; this.engine.setStyle(this._styleUrl()); }
@@ -27162,6 +27657,33 @@ function smapCreateSdk(engine) {
27162
27657
  };
27163
27658
 
27164
27659
  /** Shows buildings in 3D (and tilts the map when it is flat). */
27660
+ /**
27661
+ * Auto Zoom: a click on pins piled up zooms the map in around it, or lists them close up (see marker.overlap).
27662
+ * On by default (`autoZoom: false` in the options turns it off).
27663
+ */
27664
+ SMap.prototype.setAutoZoom = function (on) { this._autoZoom = !!on; return this; };
27665
+ SMap.prototype.autoZoom = function () { return this._autoZoom; };
27666
+
27667
+ /**
27668
+ * In 3D (3D buildings on, or the map tilted) W / S tilt the view and A / D turn it; Shift takes bigger steps. Only
27669
+ * while the map has the keyboard focus, so typing elsewhere on the page is never taken.
27670
+ */
27671
+ SMap.prototype._keyboard3D = function () {
27672
+ var self = this, m = this.engine;
27673
+ var el = m.getCanvasContainer ? m.getCanvasContainer() : (m.getContainer ? m.getContainer() : null);
27674
+ if (!el || !el.addEventListener || this._wasd === false) { return; }
27675
+ el.addEventListener('keydown', function (e) {
27676
+ if (e.altKey || e.ctrlKey || e.metaKey) { return; }
27677
+ if (!self._buildings && m.getPitch() < 1) { return; }
27678
+ var big = e.shiftKey, key = (e.key || '').toLowerCase();
27679
+ var pitch = m.getPitch(), bearing = m.getBearing();
27680
+ if (key === 'w') { pitch = Math.min(85, pitch + (big ? 15 : 5)); } else if (key === 's') { pitch = Math.max(0, pitch - (big ? 15 : 5)); }
27681
+ else if (key === 'a') { bearing -= big ? 45 : 15; } else if (key === 'd') { bearing += big ? 45 : 15; } else { return; }
27682
+ e.preventDefault();
27683
+ m.easeTo({ pitch: pitch, bearing: bearing, duration: 200 });
27684
+ });
27685
+ };
27686
+
27165
27687
  SMap.prototype.setBuildings3D = function (on, options) {
27166
27688
  this._buildings = !!on;
27167
27689
  this._buildingOptions = options || this._buildingOptions || {};
@@ -27200,8 +27722,9 @@ function smapCreateSdk(engine) {
27200
27722
  * @param {Object|Array} data GeoJSON, or an array of {lng, lat, …properties}
27201
27723
  * @param {Object} [o]
27202
27724
  * cluster: true | {radius, maxZoom}; color; radius; strokeColor; icon (image URL); iconSize; label (property name);
27203
- * minzoom; maxzoom; zIndex (higher draws on top); onClick(feature, event); popup(properties) → trusted HTML
27204
- * (inserted as is, never sanitized: escape feature data) or a DOM node
27725
+ * minzoom; maxzoom; zIndex (higher draws on top); onClick(feature, event);
27726
+ * popup(properties, feature) → trusted HTML (inserted as is, never sanitized: escape feature data, or use
27727
+ * sMap.popupTemplate), a DOM node, or a promise of either; popupOptions (over the map's `popup`); popupLoading
27205
27728
  */
27206
27729
  SMap.prototype.addPoints = function (id, data, o) {
27207
27730
  o = o || {};
@@ -27229,6 +27752,7 @@ function smapCreateSdk(engine) {
27229
27752
  var def = this._layers[id];
27230
27753
  if (!def) { throw new Error('sMap: no layer ' + id); }
27231
27754
  def.data = toFeatureCollection(data);
27755
+ if (def.hovered) { this._setHover(id, def, null); }
27232
27756
  var src = this.engine.getSource('smap-' + id);
27233
27757
  if (src) { src.setData(def.data); }
27234
27758
  return this;
@@ -27307,7 +27831,9 @@ function smapCreateSdk(engine) {
27307
27831
  if (!m) { return; }
27308
27832
  def.engineLayers.forEach(function (l) { if (m.getLayer(l)) { m.removeLayer(l); } });
27309
27833
  if (m.getSource('smap-' + id)) { m.removeSource('smap-' + id); }
27310
- (this._handlers[id] || []).forEach(function (h) { m.off(h[0], h[1], h[2]); });
27834
+ if (m.getSource('smap-' + id + '-hover')) { m.removeSource('smap-' + id + '-hover'); }
27835
+ def.hoverLayer = null; def.hovered = null;
27836
+ (this._handlers[id] || []).forEach(function (h) { if (h[1]) { m.off(h[0], h[1], h[2]); } else { m.off(h[0], h[2]); } });
27311
27837
  this._handlers[id] = [];
27312
27838
  def.engineLayers = [];
27313
27839
  };
@@ -27340,7 +27866,11 @@ function smapCreateSdk(engine) {
27340
27866
  layer.source = src;
27341
27867
  // The engine refuses a filter key whose value is undefined (unclustered points have none).
27342
27868
  if (layer.filter === undefined) { delete layer.filter; }
27343
- for (var k in range) { layer[k] = range[k]; }
27869
+ if (layer.minzoom === undefined) { delete layer.minzoom; }
27870
+ if (layer.maxzoom === undefined) { delete layer.maxzoom; }
27871
+ if (layer.paint === undefined) { delete layer.paint; }
27872
+ // A layer's own minzoom (a marker's textMinzoom / badgeMinzoom) never shows it before the layer's own range.
27873
+ for (var k in range) { layer[k] = k === 'minzoom' && layer.minzoom !== undefined ? Math.max(layer.minzoom, range.minzoom) : range[k]; }
27344
27874
  layer.layout = Object.assign({ visibility: visibility }, layer.layout || {});
27345
27875
  m.addLayer(layer, before);
27346
27876
  def.engineLayers.push(layer.id);
@@ -27370,7 +27900,64 @@ function smapCreateSdk(engine) {
27370
27900
  });
27371
27901
  }
27372
27902
  var only = o.cluster ? ['!', ['has', 'point_count']] : undefined;
27373
- if (o.icon) {
27903
+ var both = function (extra) { return only ? ['all', only, extra] : extra; };
27904
+ if (o.marker) {
27905
+ // Pins like Superroute's route map, drawn on the GPU: one image per colour pair (and per number, per badge),
27906
+ // made the first time a feature shows it. Numbers and badges are their own layers above the pins.
27907
+ var mk = o.marker;
27908
+ var shape = mk.shape === 'circle' || mk.shape === 'vehicle' ? mk.shape : 'pin';
27909
+ var size = mk.size || 32;
27910
+ var bw = mk.borderWidth !== undefined ? mk.borderWidth : 3;
27911
+ var g = markerGeometry(shape, size);
27912
+ var str = function (v, d) { return ['to-string', valueExpr(v, d)]; };
27913
+ // One scale for the pin, its number and its badge (a number, or an engine expression such as one of the zoom),
27914
+ // so the three stay together at every size: the offsets are in icon units and scale with them.
27915
+ var scale = mk.scale !== undefined ? mk.scale : 1;
27916
+ // Opacity of the pin, its number and its badge together (the route map draws settled stops at .72).
27917
+ var markerPaint = mk.opacity !== undefined ? { 'icon-opacity': valueExpr(mk.opacity, 1) } : undefined;
27918
+ main = src + '-points';
27919
+ // From bakeZoom on (default 13) a pin's number is drawn into its own image, so an upper pin covers a lower
27920
+ // one completely. Further out, where thousands of pins can be in view, the numbers stay one layer above the
27921
+ // pins (an image per colour pair instead of per pin and number). bakeZoom: false keeps them separate.
27922
+ var plainPin = drawnImageId('pin', [shape, str(mk.fill, '#ffffff'), str(mk.border, color), String(bw), String(size)]);
27923
+ var bakeZoom = mk.text !== undefined && mk.bakeZoom !== false ? (mk.bakeZoom !== undefined ? mk.bakeZoom : 13) : null;
27924
+ var pinImage = bakeZoom === null ? plainPin : ['step', ['zoom'], plainPin, bakeZoom,
27925
+ drawnImageId('pinnum', [shape, str(mk.fill, '#ffffff'), str(mk.border, color), String(bw), String(size), str(mk.textColor, '#ffffff'), str(mk.text, '')])];
27926
+ var markerSpecs = [];
27927
+ var addMarker = function (layer) { markerSpecs.push(JSON.parse(JSON.stringify(layer))); add(layer); };
27928
+ addMarker({
27929
+ id: main, type: 'symbol', filter: only, paint: markerPaint,
27930
+ layout: {
27931
+ 'icon-image': pinImage,
27932
+ 'icon-anchor': shape === 'pin' ? 'bottom' : 'center',
27933
+ // The image has room for the shadow below the tip: the tip, not the image's edge, is at the position.
27934
+ 'icon-offset': [0, shape === 'pin' ? PIN_PAD : 0], 'icon-size': scale,
27935
+ 'icon-allow-overlap': true, 'icon-ignore-placement': true,
27936
+ },
27937
+ });
27938
+ if (mk.text !== undefined) {
27939
+ var text = str(mk.text, '');
27940
+ addMarker({
27941
+ id: src + '-numbers', type: 'symbol', filter: both(['!=', text, '']), minzoom: mk.textMinzoom, maxzoom: bakeZoom === null ? undefined : bakeZoom, paint: markerPaint,
27942
+ layout: {
27943
+ 'icon-image': drawnImageId('num', [str(mk.textColor, '#ffffff'), String(size), text]),
27944
+ 'icon-offset': [0, -g.tipToHead], 'icon-size': scale, 'icon-allow-overlap': true, 'icon-ignore-placement': true,
27945
+ },
27946
+ });
27947
+ }
27948
+ if (mk.badge !== undefined) {
27949
+ var badge = ['to-number', valueExpr(mk.badge, 0), 0];
27950
+ addMarker({
27951
+ id: src + '-badges', type: 'symbol', filter: both(['>', badge, 1]), minzoom: mk.badgeMinzoom, paint: markerPaint,
27952
+ layout: {
27953
+ 'icon-image': drawnImageId('badge', [['to-string', badge]]),
27954
+ 'icon-offset': g.badge, 'icon-size': scale,
27955
+ 'icon-allow-overlap': true, 'icon-ignore-placement': true,
27956
+ },
27957
+ });
27958
+ }
27959
+ if (mk.hoverRaise !== false) { this._hoverRaise(id, def, src, markerSpecs, main); }
27960
+ } else if (o.icon) {
27374
27961
  var imageId = src + '-icon';
27375
27962
  main = src + '-points';
27376
27963
  var placeIcon = function () {
@@ -27398,15 +27985,43 @@ function smapCreateSdk(engine) {
27398
27985
  if (o.label) {
27399
27986
  add({
27400
27987
  id: src + '-labels', type: 'symbol', filter: only,
27401
- layout: { 'text-field': ['to-string', ['get', o.label]], 'text-font': ['Noto Sans Regular'], 'text-size': 12, 'text-offset': [0, 1.2], 'text-anchor': 'top', 'text-optional': true },
27988
+ layout: o.labelPosition === 'right'
27989
+ ? { 'text-field': ['to-string', ['get', o.label]], 'text-font': ['Noto Sans Regular'], 'text-size': 11, 'text-offset': [1.3, 0], 'text-anchor': 'left', 'text-optional': true, 'text-max-width': 12 }
27990
+ : { 'text-field': ['to-string', ['get', o.label]], 'text-font': ['Noto Sans Regular'], 'text-size': 12, 'text-offset': [0, 1.2], 'text-anchor': 'top', 'text-optional': true },
27402
27991
  paint: { 'text-color': '#1f2937', 'text-halo-color': '#ffffff', 'text-halo-width': 1.4 },
27403
27992
  });
27404
27993
  }
27405
27994
  } else if (def.kind === 'lines') {
27406
27995
  main = src + '-lines';
27407
- var paint = { 'line-color': color, 'line-width': o.width || 3, 'line-opacity': o.opacity !== undefined ? o.opacity : 1 };
27996
+ var lineColor = valueExpr(o.color, '#4f46e5');
27997
+ var round = { 'line-cap': 'round', 'line-join': 'round' };
27998
+ // Bottom to top: casing, shadow, the line, its arrows (as on Superroute's route map).
27999
+ if (o.casing) {
28000
+ var cs = o.casing === true ? {} : o.casing;
28001
+ add({ id: src + '-casing', type: 'line', layout: round, paint: {
28002
+ 'line-color': valueExpr(cs.color, '#ffffff'), 'line-width': cs.width || 9, 'line-opacity': cs.opacity !== undefined ? cs.opacity : 1 } });
28003
+ }
28004
+ if (o.shadow) {
28005
+ var sh = o.shadow === true ? {} : o.shadow;
28006
+ add({ id: src + '-shadow', type: 'line', layout: round, paint: {
28007
+ 'line-color': valueExpr(sh.color, '#000000'), 'line-width': sh.width || 7, 'line-opacity': sh.opacity !== undefined ? sh.opacity : 0.3 } });
28008
+ }
28009
+ var paint = { 'line-color': lineColor, 'line-width': o.width || 3, 'line-opacity': o.opacity !== undefined ? o.opacity : 1 };
27408
28010
  if (o.dash) { paint['line-dasharray'] = o.dash; }
27409
- add({ id: main, type: 'line', layout: { 'line-cap': 'round', 'line-join': 'round' }, paint: paint });
28011
+ add({ id: main, type: 'line', layout: round, paint: paint });
28012
+ if (o.arrows) {
28013
+ var ar = o.arrows === true ? {} : o.arrows;
28014
+ var arrowSize = ar.size || 14;
28015
+ add({
28016
+ id: src + '-arrows', type: 'symbol',
28017
+ layout: {
28018
+ 'symbol-placement': 'line', 'symbol-spacing': ar.spacing || 80,
28019
+ 'icon-image': drawnImageId('arrow', [String(arrowSize), ['to-string', valueExpr(ar.color, lineColor)]]),
28020
+ 'icon-rotation-alignment': 'map', 'icon-allow-overlap': true, 'icon-ignore-placement': true,
28021
+ },
28022
+ paint: { 'icon-opacity': ar.opacity !== undefined ? ar.opacity : 0.8 },
28023
+ });
28024
+ }
27410
28025
  } else {
27411
28026
  if (o.extrude) {
27412
28027
  main = src + '-extrusion';
@@ -27426,32 +28041,75 @@ function smapCreateSdk(engine) {
27426
28041
  add({ id: src + '-outline', type: 'line', paint: { 'line-color': o.outline || o.fill || color, 'line-width': o.outlineWidth || 1.5 } });
27427
28042
  }
27428
28043
  }
28044
+ // The popup is opened by the map's one click handler (_popupClick), from this layer's own hit test.
28045
+ def.popupLayer = o.popup ? main : null;
27429
28046
  if (main && (o.popup || o.onClick)) {
27430
- this._listen(id, 'click', main, function (e) {
27431
- var f = e.features[0];
27432
- if (o.onClick) { o.onClick(f, e); }
27433
- if (o.popup) {
27434
- // A string is inserted as HTML as it is (never sanitized): it must be trusted, with feature data escaped.
27435
- // A DOM node is inserted as it is.
27436
- var content = o.popup(f.properties, f);
27437
- if (content) {
27438
- var popup = new engine.Popup({ offset: 12 }).setLngLat(e.lngLat);
27439
- if (typeof content === 'string') { popup.setHTML(content); } else { popup.setDOMContent(content); }
27440
- popup.addTo(m);
27441
- }
27442
- }
27443
- });
28047
+ if (o.onClick) {
28048
+ this._listen(id, 'click', main, function (e) { o.onClick(e.features[0], e); });
28049
+ }
27444
28050
  this._listen(id, 'mouseenter', main, function () { m.getCanvas().style.cursor = 'pointer'; });
27445
28051
  this._listen(id, 'mouseleave', main, function () { m.getCanvas().style.cursor = ''; });
27446
28052
  }
27447
28053
  };
27448
28054
 
28055
+ /**
28056
+ * Overlapping pins: the one under the pointer comes to the front, as on Superroute's route map, so it can be read
28057
+ * and clicked. A copy of that one feature is drawn in its own source above everything else; nothing is done per
28058
+ * feature, only for the feature under the pointer.
28059
+ */
28060
+ SMap.prototype._hoverRaise = function (id, def, src, specs, main) {
28061
+ var m = this.engine, self = this;
28062
+ var hoverSrc = src + '-hover';
28063
+ m.addSource(hoverSrc, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
28064
+ var top = null;
28065
+ specs.forEach(function (spec) {
28066
+ var layer = JSON.parse(JSON.stringify(spec));
28067
+ layer.id = spec.id.replace(src + '-', src + '-hover-');
28068
+ layer.source = hoverSrc;
28069
+ if (layer.filter === undefined) { delete layer.filter; }
28070
+ if (layer.paint === undefined) { delete layer.paint; }
28071
+ if (layer.minzoom === undefined) { delete layer.minzoom; }
28072
+ if (layer.maxzoom === undefined) { delete layer.maxzoom; }
28073
+ m.addLayer(layer);
28074
+ def.engineLayers.push(layer.id);
28075
+ if (!top) { top = layer.id; }
28076
+ });
28077
+ def.hoverLayer = top;
28078
+ def.hoverSource = hoverSrc;
28079
+ var keyOf = function (f) { return JSON.stringify(f.geometry && f.geometry.coordinates) + JSON.stringify(f.properties || {}); };
28080
+ this._listen(id, 'mousemove', null, function (e) {
28081
+ if (def.hidden || !m.getLayer(main) || def.pinned) { return; }
28082
+ // Still over the raised pin: keep it. Otherwise raise the top pin under the pointer, if any.
28083
+ if (def.hovered && m.getLayer(top) && m.queryRenderedFeatures(e.point, { layers: [top] }).length) { return; }
28084
+ var hits = m.queryRenderedFeatures(e.point, { layers: [main] });
28085
+ var f = hits && hits[0];
28086
+ if (!f) { if (def.hovered) { self._setHover(id, def, null); } return; }
28087
+ if (def.hovered && def.hovered.key === keyOf(f)) { return; }
28088
+ self._setHover(id, def, f, keyOf(f));
28089
+ });
28090
+ this._listen(id, 'mouseout', null, function () { if (def.hovered && !def.pinned) { self._setHover(id, def, null); } });
28091
+ };
28092
+
28093
+ SMap.prototype._unpin = function () {
28094
+ var def = this._pinnedDef;
28095
+ this._pinnedDef = null;
28096
+ if (def) { def.pinned = null; this._setHover(null, def, null); }
28097
+ };
28098
+
28099
+ SMap.prototype._setHover = function (id, def, f, key) {
28100
+ var source = def.hoverSource && this.engine.getSource(def.hoverSource);
28101
+ def.hovered = f ? { key: key } : null;
28102
+ if (!source) { return; }
28103
+ // A plain copy: the engine's own feature objects cannot be sent to its worker.
28104
+ source.setData({ type: 'FeatureCollection', features: f ? [JSON.parse(JSON.stringify({ type: 'Feature', properties: f.properties || {}, geometry: f.geometry }))] : [] });
28105
+ };
28106
+
27449
28107
  SMap.prototype._listen = function (id, type, layer, fn) {
27450
- this.engine.on(type, layer, fn);
28108
+ if (layer) { this.engine.on(type, layer, fn); } else { this.engine.on(type, fn); }
27451
28109
  (this._handlers[id] = this._handlers[id] || []).push([type, layer, fn]);
27452
28110
  };
27453
28111
 
27454
- return { Map: SMap, version: VERSION, styles: FLAVORS.slice(), engine: engine };
28112
+ return { Map: SMap, version: VERSION, styles: FLAVORS.slice(), engine: engine, popupTemplate: popupTemplate };
27455
28113
  });
27456
28114
 
27457
28115
  return module.exports;
@@ -27471,10 +28129,16 @@ function SMapMap(options) {
27471
28129
  SMapMap.prototype = core.Map.prototype;
27472
28130
  return new core.Map(options);
27473
28131
  }
27474
- var smapVersion = "1.0.2";
28132
+ var smapVersion = "1.0.6";
27475
28133
  var smapStyles = ['light', 'white', 'grayscale', 'dark', 'black'];
27476
28134
  /** The bundled rendering engine, for anything the SDK does not wrap (loaded on the first call). */
27477
28135
  function smapGetEngine() { return smapLoad().engine; }
27478
- var smapDefault = { Map: SMapMap, version: smapVersion, styles: smapStyles, getEngine: smapGetEngine };
27479
- export { SMapMap as Map, smapVersion as version, smapStyles as styles, smapGetEngine as getEngine };
28136
+ // Templates need no engine: before the first map they come from an SDK made without one.
28137
+ var smapNoEngine = null;
28138
+ function smapPopupTemplate(template) {
28139
+ if (!smapCore && !smapNoEngine) { smapNoEngine = smapCreateSdk(null); }
28140
+ return (smapCore || smapNoEngine).popupTemplate(template);
28141
+ }
28142
+ var smapDefault = { Map: SMapMap, version: smapVersion, styles: smapStyles, getEngine: smapGetEngine, popupTemplate: smapPopupTemplate };
28143
+ export { SMapMap as Map, smapVersion as version, smapStyles as styles, smapGetEngine as getEngine, smapPopupTemplate as popupTemplate };
27480
28144
  export default smapDefault;