1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';
import React, { useRef, useLayoutEffect, useEffect, useState } from 'react';
import { deviceCategories } from '../common/deviceCategories';
import { loadIcon, loadImage } from './mapUtil';
const element = document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
export const map = new mapboxgl.Map({
container: element,
style: {
version: 8,
sources: {
osm: {
type: 'raster',
tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
tileSize: 256,
attribution: '© <a target="_top" rel="noopener" href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
},
},
glyphs: 'https://cdn.traccar.com/map/fonts/{fontstack}/{range}.pbf',
layers: [{
id: 'osm',
type: 'raster',
source: 'osm',
}],
},
});
map.addControl(new mapboxgl.NavigationControl());
let readyListeners = [];
const onMapReady = listener => {
if (!readyListeners) {
listener();
} else {
readyListeners.push(listener);
}
};
map.on('load', async () => {
const background = await loadImage('images/background.svg');
await Promise.all(deviceCategories.map(async category => {
const imageData = await loadIcon(category, background, `images/icon/${category}.svg`);
map.addImage(category, imageData, { pixelRatio: window.devicePixelRatio });
}));
if (readyListeners) {
readyListeners.forEach(listener => listener());
readyListeners = null;
}
});
const Map = ({ children }) => {
const containerEl = useRef(null);
const [mapReady, setMapReady] = useState(false);
useEffect(() => onMapReady(() => setMapReady(true)), []);
useLayoutEffect(() => {
const currentEl = containerEl.current;
currentEl.appendChild(element);
if (map) {
map.resize();
}
return () => {
currentEl.removeChild(element);
};
}, [containerEl]);
return (
<div style={{ width: '100%', height: '100%' }} ref={containerEl}>
{mapReady && children}
</div>
);
};
export default Map;
|