forked from toggle-corp/re-map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapImage.tsx
99 lines (86 loc) · 2.71 KB
/
MapImage.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { useContext, useEffect, useState } from 'react';
import { MapChildContext } from './context';
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
type Props = {
name: string;
url: string;
imageOptions?: { pixelRatio?: number; sdf?: boolean };
onLoad?: (loaded: boolean) => void;
} | {
name: string;
image: Img;
imageOptions?: { pixelRatio?: number; sdf?: boolean };
onLoad?: (loaded: boolean) => void;
}
type Img = HTMLImageElement
| ArrayBufferView
| { width: number; height: number; data: Uint8Array | Uint8ClampedArray }
| ImageData;
const MapImage = (props: Props) => {
const { map, isMapDestroyed, mapStyle } = useContext(MapChildContext);
const {
name,
url,
image,
imageOptions,
onLoad,
} = props;
const [initialName] = useState(name);
const [initialUrl] = useState(url);
const [initialImage] = useState(image);
const [initialImageOptions] = useState(imageOptions);
// Handle change in bounds
useEffect(
() => {
if (!map || !mapStyle) {
return noop;
}
if (map.hasImage(initialName)) {
console.warn(`An image with name '${initialName}' already exists`);
} else if (initialUrl) {
if (onLoad) {
onLoad(false);
}
map.loadImage(
initialUrl,
(error: unknown, loadedImage: Img) => {
if (isMapDestroyed()) {
return;
}
if (error) {
console.error(error);
return;
}
map.addImage(initialName, loadedImage, initialImageOptions);
if (onLoad) {
onLoad(true);
}
},
);
} else if (initialImage) {
map.addImage(initialName, initialImage, initialImageOptions);
if (onLoad) {
onLoad(true);
}
}
return () => {
if (!isMapDestroyed() && map.hasImage(initialName)) {
map.removeImage(initialName);
if (onLoad) {
onLoad(false);
}
}
};
},
[
map, mapStyle, isMapDestroyed,
initialName, initialImage, initialUrl, initialImageOptions,
onLoad,
],
);
return null;
};
MapImage.defaultProps = {
};
export default MapImage;