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