solid-map-gl 1.12.0 → 2.0.0

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.
Files changed (62) hide show
  1. package/README.md +157 -30
  2. package/dist/index.d.ts +489 -0
  3. package/dist/index.js +11 -0
  4. package/dist/index.jsx +2320 -0
  5. package/package.json +46 -35
  6. package/dist/esm/index.js +0 -2
  7. package/dist/esm/index.js.map +0 -1
  8. package/dist/source/components/Atmosphere/index.jsx +0 -13
  9. package/dist/source/components/Camera/index.jsx +0 -108
  10. package/dist/source/components/Control/index.jsx +0 -33
  11. package/dist/source/components/Draw/drawingStyles.js +0 -225
  12. package/dist/source/components/Draw/index.jsx +0 -55
  13. package/dist/source/components/Draw/modes/index.js +0 -9
  14. package/dist/source/components/Draw/modes/line_string.js +0 -43
  15. package/dist/source/components/Draw/modes/measurements.js +0 -76
  16. package/dist/source/components/Draw/modes/multi_point.js +0 -37
  17. package/dist/source/components/Draw/modes/point.js +0 -25
  18. package/dist/source/components/Draw/modes/polygon.js +0 -25
  19. package/dist/source/components/Draw/modes/radius.js +0 -138
  20. package/dist/source/components/Draw/modes/rectangle.js +0 -118
  21. package/dist/source/components/Draw/modes/rectangle_assisted.js +0 -233
  22. package/dist/source/components/Image/index.jsx +0 -135
  23. package/dist/source/components/Layer/index.jsx +0 -125
  24. package/dist/source/components/Layer3D/index.jsx +0 -330
  25. package/dist/source/components/Light/index.jsx +0 -10
  26. package/dist/source/components/MapGL/index.jsx +0 -272
  27. package/dist/source/components/MapProvider/index.jsx +0 -9
  28. package/dist/source/components/Marker/index.jsx +0 -57
  29. package/dist/source/components/Popup/index.jsx +0 -38
  30. package/dist/source/components/Source/index.jsx +0 -89
  31. package/dist/source/components/Terrain/index.jsx +0 -30
  32. package/dist/source/events.js +0 -78
  33. package/dist/source/index.jsx +0 -14
  34. package/dist/source/mapStyles.js +0 -116
  35. package/dist/source/styles.js +0 -62
  36. package/dist/types/components/Atmosphere/index.d.ts +0 -8
  37. package/dist/types/components/Camera/index.d.ts +0 -54
  38. package/dist/types/components/Control/index.d.ts +0 -15
  39. package/dist/types/components/Draw/drawingStyles.d.ts +0 -20
  40. package/dist/types/components/Draw/index.d.ts +0 -16
  41. package/dist/types/components/Draw/modes/index.d.ts +0 -6
  42. package/dist/types/components/Draw/modes/line_string.d.ts +0 -2
  43. package/dist/types/components/Draw/modes/multi_point.d.ts +0 -2
  44. package/dist/types/components/Draw/modes/point.d.ts +0 -2
  45. package/dist/types/components/Draw/modes/polygon.d.ts +0 -2
  46. package/dist/types/components/Draw/modes/radius.d.ts +0 -2
  47. package/dist/types/components/Draw/modes/rectangle.d.ts +0 -2
  48. package/dist/types/components/Draw/modes/rectangle_assisted.d.ts +0 -18
  49. package/dist/types/components/Image/index.d.ts +0 -28
  50. package/dist/types/components/Layer/index.d.ts +0 -32
  51. package/dist/types/components/Layer3D/index.d.ts +0 -22
  52. package/dist/types/components/Light/index.d.ts +0 -8
  53. package/dist/types/components/MapGL/index.d.ts +0 -95
  54. package/dist/types/components/MapProvider/index.d.ts +0 -11
  55. package/dist/types/components/Marker/index.d.ts +0 -28
  56. package/dist/types/components/Popup/index.d.ts +0 -18
  57. package/dist/types/components/Source/index.d.ts +0 -13
  58. package/dist/types/components/Terrain/index.d.ts +0 -7
  59. package/dist/types/events.d.ts +0 -103
  60. package/dist/types/index.d.ts +0 -16
  61. package/dist/types/mapStyles.d.ts +0 -2
  62. package/dist/types/styles.d.ts +0 -2
@@ -1,330 +0,0 @@
1
- import { onCleanup, createUniqueId, createSignal, onMount, createContext, useContext, } from "solid-js";
2
- import { useMapContext } from "../MapProvider";
3
- const deg2rad = (degrees) => {
4
- return (degrees * Math.PI) / 180;
5
- };
6
- const latLng2Mercator = (lat, lng, altitude) => {
7
- const R = 6378137.0; // earth radius in meters
8
- const x = R * deg2rad(lng);
9
- const y = R * Math.log(Math.tan(Math.PI / 4 + deg2rad(lat) / 2));
10
- return [x, y, altitude];
11
- };
12
- const latLng2Cartesian = ({ lat, lng }, altitude = 0) => {
13
- const R = 6378137.0; // earth radius in meters
14
- const x = R * Math.cos(deg2rad(lat)) * Math.cos(deg2rad(lng));
15
- const y = R * Math.cos(deg2rad(lat)) * Math.sin(deg2rad(lng));
16
- const z = altitude; // + R * Math.sin(deg2rad(lat));
17
- return { x, y, z };
18
- };
19
- const LayerContext = createContext();
20
- export const useScene = () => useContext(LayerContext);
21
- export const Layer3D = (props) => {
22
- const [ctx] = useMapContext();
23
- const [scene, setScene] = createSignal(null);
24
- onMount(async () => {
25
- props.id = props.id || createUniqueId();
26
- const worldOriginMercator = window.MapLib.MercatorCoordinate.fromLngLat([props.origin[0] || 0, props.origin[1] || 0], props.origin[2] || 0);
27
- const worldScale = worldOriginMercator.meterInMercatorCoordinateUnits();
28
- const { x, y, z } = worldOriginMercator;
29
- let worldMatrix = null;
30
- let BABYLON = null;
31
- let THREE = null;
32
- if (props.babylon) {
33
- BABYLON = await import("@babylonjs/core");
34
- worldMatrix = BABYLON.Matrix.Compose(new BABYLON.Vector3(worldScale, worldScale, worldScale), BABYLON.Quaternion.FromEulerAngles(Math.PI / 2, 0, 0), new BABYLON.Vector3(x, y, z));
35
- }
36
- else {
37
- THREE = await import("three");
38
- worldMatrix = {
39
- translateX: x,
40
- translateY: y,
41
- translateZ: z,
42
- rotateX: Math.PI / 2,
43
- rotateY: 0,
44
- rotateZ: 0,
45
- scale: worldScale,
46
- };
47
- }
48
- ctx.map.addLayer({
49
- id: props.id,
50
- type: "custom",
51
- renderingMode: "3d",
52
- onAdd(map, gl) {
53
- if (props.babylon) {
54
- const engine = new BABYLON.Engine(gl, true, {
55
- useHighPrecisionMatrix: true,
56
- }, true);
57
- // this.index = 0;
58
- this.scene = new BABYLON.Scene(engine);
59
- this.scene.autoClear = false;
60
- // this.scene.autoClearDepthAndStencil = false;
61
- // this.scene.detachControl();
62
- this.scene.preventDefaultOnPointerDown = false;
63
- this.scene.preventDefaultOnPointerUp = false;
64
- // this.scene.beforeRender = () => engine.wipeCaches(true);
65
- const camera = new BABYLON.UniversalCamera("Camera", BABYLON.Vector3.Zero());
66
- camera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
67
- camera.inertia = 0;
68
- // this.scene.activeCamera.setTarget(new BABYLON.Vector3(-1, 0, 0));
69
- // this.scene.activeCamera.rotationQuaternion =
70
- // BABYLON.Quaternion.Identity();
71
- // this.scene.activeCamera.updateUpVectorFromRotation = true;
72
- // this.scene.activeCamera.noRotationConstraint = true;
73
- // this.scene.activeCamera.inputs.addMouseWheel();
74
- // this.scene.activeCamera.setTarget(BABYLON.Vector3.Zero());
75
- // setTimeout(() => {
76
- // this.scene.activeCamera.setPosition(
77
- // new BABYLON.Vector3(100, 100, 100),
78
- // );
79
- // }, 2000);
80
- // this.scene.activeCamera.attachControl(gl.canvas, true);
81
- this.scene.ambientColor = new BABYLON.Color3(1, 1, 1);
82
- if (props.defaultLight)
83
- new BABYLON.HemisphericLight("Light", new BABYLON.Vector3(100, 10, 0), this.scene);
84
- // this.scene.root_node = new BABYLON.TransformNode("rootNode");
85
- // this.scene.root_node.lookAt(BABYLON.Vector3.Down());
86
- // this.scene.root_node.addRotation(0, 0, Math.PI / 2);
87
- // const axis = new BABYLON.AxesViewer(this.scene, 100);
88
- }
89
- else {
90
- this.camera = new THREE.Camera();
91
- this.scene = new THREE.Scene();
92
- if (props.defaultLight) {
93
- this.light = new THREE.DirectionalLight(0xffffff);
94
- this.light.position.set(100, 0, 0).normalize();
95
- this.scene.add(this.light);
96
- }
97
- this.renderer = new THREE.WebGLRenderer({
98
- canvas: map.getCanvas(),
99
- context: gl,
100
- antialias: true,
101
- });
102
- this.renderer.autoClear = false;
103
- }
104
- this.map = map;
105
- props.onAdd && props.onAdd(this.scene, this.map, gl);
106
- setScene(this.scene);
107
- },
108
- render(gl, matrix) {
109
- if (props.babylon) {
110
- this.scene.activeCamera.freezeProjectionMatrix(
111
- // props.disableProjectionMatrix
112
- // ? BABYLON.Matrix.FromArray(matrix)
113
- worldMatrix.multiply(BABYLON.Matrix.FromArray(matrix)));
114
- // this.scene.activeCamera.position =
115
- // BABYLON.Vector3.TransformCoordinates(
116
- // new BABYLON.Vector3(),
117
- // worldMatrix.multiply(BABYLON.Matrix.FromArray(matrix)).invert(),
118
- // );
119
- // this.scene.activeCamera.rotation.z = matrix[0];
120
- // this.scene.activeCamera.rotation.x = matrix[1];
121
- // this.scene.activeCamera.rotation.y = matrix[2];
122
- // console.log(this.scene.activeCamera.getProjectionMatrix(), matrix);
123
- // const m = matrix;
124
- // const transform = BABYLON.Matrix.FromArray(matrix);
125
- // console.log(transform);
126
- //
127
- // const center = this.map.getCenter();
128
- // const zoom = this.map.getZoom();
129
- // const scale = Math.pow(2, zoom);
130
- // const centerX = center.lng * scale;
131
- // const centerZ = center.lat * scale;
132
- // this.scene.activeCamera.position.x = centerX;
133
- // this.scene.activeCamera.position.z = centerZ;
134
- // this.scene.activeCamera.getWorldMatrix().copyFrom(transform);
135
- const pitch = this.map.getPitch() * (Math.PI / 180);
136
- const bearing = this.map.getBearing() * (Math.PI / 180);
137
- // this.scene.activeCamera.rotation.x = Math.asin(pitch);
138
- // this.scene.activeCamera.rotation.y = Math.atan(bearing / pitch);
139
- // this.scene.activeCamera.rotation.z = -bearing;
140
- // this.scene.activeCamera
141
- // .getWorldMatrix()
142
- // .invertToRef(this.scene.activeCamera.getViewMatrix());
143
- // const cameraMatrix = BABYLON.Matrix.FromArray(matrix); //.invert();
144
- // const scaling = BABYLON.Vector3.Zero(),
145
- // rotation = BABYLON.Vector3.Zero(),
146
- // transform = BABYLON.Vector3.Zero();
147
- // cameraMatrix.decompose(scaling, rotation, transform);
148
- // const scaling2 = BABYLON.Vector3.Zero(),
149
- // rotation2 = BABYLON.Vector3.Zero(),
150
- // transform2 = BABYLON.Vector3.Zero();
151
- // worldMatrix.decompose(scaling2, rotation2, transform2);
152
- // const lng2 =
153
- // props.origin[0] -
154
- // this.map.getFreeCameraOptions().position.toLngLat().lng;
155
- // const lat2 =
156
- // props.origin[1] -
157
- // this.map.getFreeCameraOptions().position.toLngLat().lat;
158
- //
159
- // const pos = this.map.getFreeCameraOptions().position.toLngLat();
160
- // const orient = this.map.getFreeCameraOptions().orientation;
161
- // const camPos = latLng2Cartesian(
162
- // this.map.getFreeCameraOptions().position.toLngLat(),
163
- // this.map.getFreeCameraOptions().position.toAltitude(),
164
- // );
165
- // const orgPos = latLng2Cartesian({
166
- // lng: props.origin[0],
167
- // lat: props.origin[1],
168
- // });
169
- // const o = this.map.getFreeCameraOptions().orientation;
170
- // const orient = latLng2Cartesian(
171
- // new window.MapLib.MercatorCoordinate(
172
- // ...this.map.getFreeCameraOptions().orientation,
173
- // ).toLngLat(),
174
- // );
175
- // console
176
- // .log
177
- // this.map.getFreeCameraOptions().orientation,
178
- // this.map.getFreeCameraOptions().position.toLngLat(),
179
- // orgX,
180
- // camX,
181
- // camPos,
182
- // orgPos,
183
- // x,
184
- // this.scene.activeCamera.minZ,
185
- // this.scene.activeCamera.maxZ,
186
- // this.map.getFreeCameraOptions(),
187
- // this.map.getFreeCameraOptions().position.toAltitude(),
188
- // camPos.z,
189
- // orgPos.z,
190
- // camPos.z - orgPos.z,
191
- // this.scene.activeCamera.rotationQuaternion,
192
- // matrix,
193
- // camPos.z - orgPos.z,
194
- // camPos.x - orgPos.x,
195
- // camPos.y - orgPos.y,
196
- // camPos.z - orgPos.z,
197
- // this.index,
198
- // orient,
199
- // orient.x - orgPos.x,
200
- // new BABYLON.Vector3(...orient),
201
- // camY,
202
- // camZ,
203
- // pos.lng,
204
- // x2,
205
- // y2,
206
- // z2,
207
- // transform,
208
- // matrix,
209
- // cameraMatrix._m,
210
- // cameraMatrix,
211
- // new mapboxgl.MercatorCoordinate(
212
- // transform.x,
213
- // transform.y,
214
- // transform.z,
215
- // ).toLngLat(),
216
- // worldOriginMercator.toLngLat(),
217
- // this.map.getFreeCameraOptions().position.toLngLat(),
218
- // this.map.getFreeCameraOptions().orientation,
219
- // BABYLON.Quaternion.FromArray(
220
- // this.map.getFreeCameraOptions().orientation,
221
- // ),
222
- // this.scene.activeCamera.rotationQuaternion,
223
- // BABYLON.Vector3.FromArray(
224
- // this.map.getFreeCameraOptions().orientation,
225
- // ),
226
- // ();
227
- // this.scene.activeCamera.freezeProjectionMatrix(
228
- // props.disableProjectionMatrix
229
- // ? BABYLON.Matrix.FromArray(matrix)
230
- // : worldMatrix.multiply(BABYLON.Matrix.FromArray(matrix)),
231
- // );
232
- //
233
- // const { x, y } = this.map.project(
234
- // new mapboxgl.MercatorCoordinate(pos.x, pos.y, pos.z).toLngLat(),
235
- // );
236
- // this.scene.activeCamera.position.y = 0; //-(camPos.x - orgPos.x);
237
- // this.scene.activeCamera.position.x = 0; //-(camPos.y - orgPos.y);
238
- // this.scene.activeCamera.position.z = -camPos.z; // - orgPos.z;
239
- // console.log(this.scene.activeCamera.position);
240
- // const [x, y, z, w] = this.map.getFreeCameraOptions().orientation;
241
- // let rotation_y = Math.atan(z / x);
242
- // if (x < 0) rotation_y += Math.PI;
243
- // rotation_y = Math.PI / 2 - rotation_y;
244
- // const rotation_x = Math.asin(-y);
245
- // const camera_up_before_rotatez = new BABYLON.Vector3(
246
- // -Math.cos(rotation_y),
247
- // 0,
248
- // Math.sin(rotation_y),
249
- // );
250
- // const rotation_z = Math.acos(
251
- // camera_up.x * camera_up_before_rotatez.x +
252
- // camera_up.y * camera_up_before_rotatez.y +
253
- // camera_up.z * camera_up_before_rotatez.z,
254
- // );
255
- // rotation_z = Math.PI / 2 - rotation_z;
256
- // if (camera_up.y < 0) rotation_z = Math.PI - rotation_z;
257
- //
258
- // this.scene.activeCamera.rotation.x = rotation_x;
259
- // this.scene.activeCamera.rotation.y = rotation_y;
260
- // this.scene.activeCamera.rotationQuaternion =
261
- // // BABYLON.Quaternion.Identity();
262
- // // BABYLON.Quaternion.FromEulerAngles(1, 0, 0);
263
- // BABYLON.Quaternion.FromArray([-x, y, -z, w]);
264
- // this.scene.activeCamera.alpha = -z;
265
- // this.scene.activeCamera.alpha = -z;
266
- // this.scene.activeCamera.radius = x; //Math.PI / 2 + this.index;
267
- // this.scene.activeCamera.radius = y;
268
- // this.index += 0.001;
269
- // BABYLON.Quaternion.RotationYawPitchRoll(-1, 1, -1);
270
- // BABYLON.Vector3.Zero();
271
- // BABYLON.Vector3.FromArray(
272
- // this.map.getFreeCameraOptions().orientation,
273
- // );
274
- // this.scene.activeCamera.setTarget(
275
- // BABYLON.Vector3.Zero(),
276
- // // new BABYLON.Vector3(
277
- // // orient.x - orgPos.x,
278
- // // 0, // orient.y - orgPos.y,
279
- // // 0, // orient.z - orgPos.z,
280
- // // ),
281
- // );
282
- // const o2 = this.map.project(
283
- // new mapboxgl.MercatorCoordinate(
284
- // orient[0],
285
- // orient[1],
286
- // orient[2],
287
- // ).toLngLat(),
288
- // );
289
- // this.camera.setTarget(new BABYLON.Vector3(o2.x, o2.y, o2.z));
290
- // console.log(
291
- // this.map.getCamera(),
292
- // this.map.project(
293
- // new mapboxgl.MercatorCoordinate(pos.x, pos.y, pos.z).toLngLat(),
294
- // ),
295
- // this.map.getFreeCameraOptions().orientation,
296
- // );
297
- // console.log(this.scene.activeCamera.position);
298
- // this.camera.position = BABYLON.Vector3.TransformCoordinates(
299
- // new BABYLON.Vector3(x, y, z),
300
- // this.scene.activeCamera.getProjectionMatrix().clone().invert(),
301
- // );
302
- this.scene.render(false);
303
- }
304
- else {
305
- const rotationX = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(1, 0, 0), worldMatrix.rotateX);
306
- const rotationY = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 1, 0), worldMatrix.rotateY);
307
- const rotationZ = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 0, 1), worldMatrix.rotateZ);
308
- const m = new THREE.Matrix4().fromArray(matrix);
309
- const l = new THREE.Matrix4()
310
- .makeTranslation(worldMatrix.translateX, worldMatrix.translateY, worldMatrix.translateZ)
311
- .scale(new THREE.Vector3(worldMatrix.scale, -worldMatrix.scale, worldMatrix.scale))
312
- .multiply(rotationX)
313
- .multiply(rotationY)
314
- .multiply(rotationZ);
315
- this.camera.projectionMatrix = m.multiply(l);
316
- this.renderer.resetState();
317
- this.renderer.render(this.scene, this.camera);
318
- }
319
- props.onRender && props.onRender(gl, matrix);
320
- ctx.map.triggerRepaint();
321
- },
322
- }, props.beforeId);
323
- });
324
- onCleanup(() => {
325
- ctx.map.getLayer(props.id) && ctx.map.removeLayer(props.id);
326
- });
327
- return (<LayerContext.Provider value={scene}>
328
- {scene() && props.children}
329
- </LayerContext.Provider>);
330
- };
@@ -1,10 +0,0 @@
1
- import { onCleanup, createEffect } from 'solid-js';
2
- import { useMapContext } from '../MapProvider';
3
- export const Light = (props) => {
4
- const [ctx] = useMapContext();
5
- // Add or Update Light Layer
6
- createEffect(() => ctx.map.setLight(props.style || {}));
7
- // Remove Light Layer
8
- onCleanup(() => ctx.map?.setLight(null));
9
- return null;
10
- };
@@ -1,272 +0,0 @@
1
- import { createSignal, createEffect, onMount, onCleanup, on, } from "solid-js";
2
- import { MapProvider } from "../MapProvider";
3
- import { mapEvents } from "../../events";
4
- import { vectorStyleList } from "../../mapStyles";
5
- /** Creates a new Map Container */
6
- export const MapGL = (props) => {
7
- let map;
8
- let mapRef;
9
- let resizeObserver;
10
- let mutationObserver;
11
- const [mapLoaded, setMapLoaded] = createSignal(null);
12
- const [darkMode, setDarkMode] = createSignal((typeof window !== "undefined" &&
13
- window.matchMedia("(prefers-color-scheme: dark)").matches) ||
14
- (typeof document !== "undefined" &&
15
- document.body.classList.contains("dark")));
16
- const [internal, setInternal] = createSignal(false);
17
- const debug = (text, value) => (props.debug || props.debugEvents) &&
18
- console.debug("%c[MapGL]", "color: #0ea5e9", text, value || "");
19
- const getStyle = (light, dark) => {
20
- const style = darkMode() && dark ? dark : light;
21
- return typeof style === "string" || style instanceof String
22
- ? style
23
- ?.split(":")
24
- .reduce((p, c) => p && p[c], vectorStyleList)
25
- ?.replace("{apikey}",
26
- //@ts-ignore
27
- props.apikey || import.meta.env.VITE_VECTOR_API_KEY) || style
28
- : style;
29
- };
30
- onMount(async () => {
31
- let mapLib = props.mapLib || (await import("mapbox-gl"));
32
- if (!mapLib.Map)
33
- mapLib = window["maplibregl"] || window["mapboxgl"];
34
- if (typeof mapLib.supported === "function" && !mapLib.supported())
35
- throw new Error("Mapbox GL not supported");
36
- debug(`Map (v${mapLib.version}) loading...`);
37
- map = new mapLib.Map({
38
- accessToken:
39
- //@ts-ignore
40
- props.options?.accessToken || import.meta.env.VITE_MAPBOX_ACCESS_TOKEN,
41
- interactive: props.options?.interactive || !!props.onViewportChange,
42
- ...props.options,
43
- ...props.viewport,
44
- projection: props.options?.projection,
45
- container: mapRef,
46
- style: getStyle(props.options?.style, props.darkStyle),
47
- fitBoundsOptions: { padding: props.viewport?.padding },
48
- });
49
- map.debug = props.debug;
50
- map.debugEvents = props.debugEvents;
51
- map.sourceIdList = [];
52
- map.layerIdList = [];
53
- window.MapLib = mapLib;
54
- // Hook up events
55
- mapEvents.forEach((item) => {
56
- const prop = props[item];
57
- if (prop) {
58
- const event = item.slice(2).toLowerCase();
59
- if (typeof prop === "function") {
60
- map.on(event, (evt) => {
61
- setTimeout(() => {
62
- if (evt.clickOnLayer)
63
- return;
64
- prop(evt);
65
- props.debugEvents && debug(`Map '${event}' event:`, evt);
66
- }, 0);
67
- });
68
- }
69
- else {
70
- Object.keys(prop).forEach((layerId) => {
71
- map.on(event, layerId, (evt) => {
72
- setTimeout(() => {
73
- if (evt.clickOnLayer)
74
- return;
75
- prop[layerId](evt);
76
- props.debugEvents &&
77
- debug(`Map '${event}' event on '${layerId}':`, evt);
78
- }, 0);
79
- });
80
- });
81
- }
82
- }
83
- });
84
- map.once("load", () => {
85
- setMapLoaded(map);
86
- debug("Map loaded");
87
- // Handle User Interaction
88
- ["mousedown", "touchstart", "wheel"].forEach((event) => map.on(event, (evt) => !evt.rotate && props.onUserInteraction?.(true)));
89
- ["moveend", "mouseup", "touchend"].forEach((event) => map.on(event, (evt) => !evt.rotate && props.onUserInteraction?.(false)));
90
- // Listen to dark theme changes
91
- const darkTheme = typeof window !== "undefined" &&
92
- window?.matchMedia("(prefers-color-scheme: dark)");
93
- darkTheme?.addEventListener("change", () => {
94
- setDarkMode(darkTheme.matches);
95
- debug("Set dark theme to:", darkTheme.matches?.toString());
96
- });
97
- mutationObserver = new MutationObserver(() => {
98
- const darkTheme = document.body.classList.contains("dark");
99
- setDarkMode(darkTheme);
100
- debug("Set theme to:", darkTheme);
101
- });
102
- mutationObserver.observe(document.body, { attributes: true });
103
- // Listen to map container size changes
104
- if (!props.disableResize) {
105
- resizeObserver = new ResizeObserver(() => {
106
- setTimeout(() => {
107
- map?.resize();
108
- }, 0);
109
- debug("Map resized");
110
- });
111
- resizeObserver.observe(mapRef);
112
- }
113
- // Update Configuration
114
- createEffect(() => {
115
- for (const key in props.config) {
116
- if (!key || key === "id")
117
- continue;
118
- const id = props.config?.id || "basemap";
119
- const value = props.config[key];
120
- //@ts-ignore
121
- map?.setConfigProperty(id, key, value);
122
- debug(`Set Config (${id}:${key}) to:`, value);
123
- }
124
- });
125
- // Update Viewport
126
- map.on("move", (event) => {
127
- const viewport = {
128
- ...props.viewport,
129
- id: props.id,
130
- point: {
131
- x: event.originalEvent?.x,
132
- y: event.originalEvent?.y,
133
- },
134
- center: props.viewport?.center?.lat
135
- ? map.getCenter()
136
- : [map.getCenter().lng, map.getCenter().lat],
137
- zoom: map.getZoom(),
138
- pitch: map.getPitch(),
139
- bearing: map.getBearing(),
140
- inTransit: true,
141
- bounds: null,
142
- // !internal()
143
- // ? props.viewport?.center?.lat
144
- // ? map.getBounds()
145
- // : [
146
- // [
147
- // map.getBounds().getNorthEast().lng,
148
- // map.getBounds().getNorthEast().lat,
149
- // ],
150
- // [
151
- // map.getBounds().getSouthWest().lng,
152
- // map.getBounds().getSouthWest().lat,
153
- // ],
154
- // ]
155
- // : null,
156
- };
157
- setInternal(true);
158
- !event.viewport && props.onViewportChange?.(viewport);
159
- });
160
- map.on("moveend", (event) => {
161
- !event.rotate &&
162
- props.onViewportChange?.({ ...props.viewport, inTransit: false });
163
- setInternal(false);
164
- });
165
- });
166
- });
167
- // Hook up viewport event
168
- createEffect(on(() => props.viewport, (vp) => {
169
- if (props.id !== vp?.id || internal())
170
- return;
171
- const viewport = {
172
- ...vp,
173
- ...(vp.bounds
174
- ? map.cameraForBounds(vp.bounds, {
175
- bearing: vp?.bearing,
176
- pitch: vp?.pitch,
177
- padding: vp?.padding,
178
- })
179
- : null),
180
- };
181
- map.stop()[props.transitionType || "flyTo"](viewport);
182
- debug(`Update Viewport (${props.transitionType || "flyTo"}):`, viewport);
183
- }, { defer: true }));
184
- // Update Projection
185
- createEffect(() => {
186
- const proj = props.options?.projection;
187
- if (!map || !proj)
188
- return;
189
- map.setProjection(proj);
190
- debug("Set Projection to:", proj);
191
- });
192
- // Update Cursor
193
- createEffect(() => {
194
- const cur = props.cursorStyle;
195
- if (!map || !cur)
196
- return;
197
- map.getCanvas().style.cursor = cur;
198
- debug("Set Cursor to:", cur);
199
- });
200
- const insertLayers = (list, layers) => {
201
- layers.forEach((layer) => {
202
- const index = list.findIndex((i) => layer.metadata.smg.beforeType
203
- ? i.type === layer.metadata.smg.beforeType
204
- : i.id === layer.metadata.smg.beforeId);
205
- list =
206
- index === -1
207
- ? [...list, layer]
208
- : [...list.slice(0, index), layer, ...list.slice(index + 1)];
209
- });
210
- return list;
211
- };
212
- // Update map style
213
- createEffect((prev) => {
214
- const style = getStyle(props.options?.style, props.darkStyle);
215
- if (map?.isStyleLoaded() && prev !== style) {
216
- const oldStyle = map.getStyle();
217
- const oldLayers = oldStyle.layers.filter((l) => map.layerIdList.includes(l.id));
218
- const oldSources = Object.keys(oldStyle.sources)
219
- .filter((s) => map.sourceIdList.includes(s))
220
- .reduce((obj, key) => ({ ...obj, [key]: oldStyle.sources[key] }), {});
221
- map.setStyle(style);
222
- map.once("styledata", () => {
223
- if (!oldLayers)
224
- return;
225
- const newStyle = map.getStyle();
226
- map.setStyle({
227
- ...newStyle,
228
- sources: { ...newStyle.sources, ...oldSources },
229
- layers: insertLayers(newStyle.layers, oldLayers),
230
- fog: oldStyle.fog,
231
- terrain: oldStyle.terrain,
232
- });
233
- debug("Set Mapstyle to:", style);
234
- });
235
- }
236
- return style;
237
- }, props.options?.style);
238
- // Update debug features
239
- [
240
- "showTileBoundaries",
241
- "showTerrainWireframe",
242
- "showCollisionBoxes",
243
- "showPadding",
244
- "showOverdrawInspector",
245
- ].forEach((item) => {
246
- createEffect(() => {
247
- const prop = props[item];
248
- if (!map || !prop)
249
- return;
250
- map[item] = prop;
251
- debug(`Set ${item} to:`, prop);
252
- });
253
- });
254
- onCleanup(() => {
255
- resizeObserver?.disconnect();
256
- mutationObserver?.disconnect();
257
- map?.remove();
258
- debug("Map removed");
259
- });
260
- return (<div ref={mapRef} id={props.id} class={props?.class} classList={props?.classList} style={props?.class || props?.classList
261
- ? null
262
- : props.style || {
263
- position: "absolute",
264
- inset: 0,
265
- "z-index": -1,
266
- }}>
267
- {mapLoaded() && (<MapProvider map={mapLoaded()}>
268
- <style>{`.overlay{position:relative;width:100%;height:100%;pointer-events:none}.overlay>*{pointer-events:auto}`}</style>
269
- <div class="overlay">{props.children}</div>
270
- </MapProvider>)}
271
- </div>);
272
- };
@@ -1,9 +0,0 @@
1
- import { createContext, useContext } from 'solid-js';
2
- import { createStore } from 'solid-js/store';
3
- const [state, setState] = createStore({ map: null });
4
- export const MapContext = createContext([state]);
5
- export const useMapContext = () => useContext(MapContext);
6
- export const MapProvider = (props) => {
7
- props.map && setState('map', props.map);
8
- return (<MapContext.Provider value={[state]}>{props.children}</MapContext.Provider>);
9
- };