使用备用图像
对于无法加载原始图像时使用备用图像;
<!DOCTYPE html>
<html lang="en">
<head>
<title>使用备用图像</title>
<meta property="og:description" content="对于无法加载原始图像时使用备用图像" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new maplibregl.Map({
container: 'map',
zoom: 10,
center: [-77.04, 38.907],
style: 'https://demotiles.maplibre.org/style.json'
});
map.on('load', () => {
// 创建一个失败图像的源
map.addSource('broken', {
"type": "image",
"url": 'https://this-image-url-does-not-exist',
"coordinates": [
[-77.13, 38.9],
[-77.0, 38.9],
[-77.0, 38.84],
[-77.13, 38.84]
]
});
// 添加图层
map.addLayer({
id: 'overlay',
'type': 'raster',
'source': 'broken',
'paint': {
'raster-opacity': 0.85
}
});
// 设置加载失败的图像处理器
map.on('error', (e) => {
// 只有特定的错误是重要的
if (
e &&
e.error &&
e.error.status === 404 &&
e.sourceId === 'broken'
) {
// 没有正确的图像,所以用一个备用图像替换源
// 这会触发raster层重绘
map.getSource('broken').updateImage({
url: 'https://picsum.photos/200/300',
coordinates: [
[-77.13, 38.9],
[-77.0, 38.9],
[-77.0, 38.84],
[-77.13, 38.84]
]
});
}
});
});
</script>
</body>
</html>