向地图添加可拉伸图片
使用可拉伸图片作为文本的背景;
<!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',
style:
'https://demotiles.maplibre.org/styles/osm-bright-gl-style/style.json',
zoom: 0.1
});
const images = {
'popup': 'https://maplibre.org/maplibre-gl-js/docs/assets/popup.png',
'popup-debug':
'https://maplibre.org/maplibre-gl-js/docs/assets/popup_debug.png'
};
map.on('load', async () => {
const debugPopup = await map.loadImage(images['popup-debug']);
const popup = await map.loadImage(images['popup']);
map.addImage('popup-debug', debugPopup.data, {
// 两列可以水平拉伸的像素(蓝色):
// - x: 25 和 x: 55 之间的像素可以拉伸
// - x: 85 和 x: 115 之间的像素可以拉伸
stretchX: [
[25, 55],
[85, 115]
],
// 一行可以垂直拉伸的像素(红色):
// - y: 25 和 y: 100 之间的像素可以拉伸
stretchY: [[25, 100]],
// 可以包含文本的图像部分([x1, y1, x2, y2]):
content: [25, 25, 115, 100],
// 这是一个高DPI图像:
pixelRatio: 2
});
map.addImage('popup', popup.data, {
stretchX: [
[25, 55],
[85, 115]
],
stretchY: [[25, 100]],
content: [25, 25, 115, 100],
pixelRatio: 2
});
map.addSource('points', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [40, -30]
},
'properties': {
'image-name': 'popup-debug',
'name': '第1行\n第2行\n第3行'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [40, 30]
},
'properties': {
'image-name': 'popup',
'name': '第1行\n第2行\n第3行'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-40, -30]
},
'properties': {
'image-name': 'popup-debug',
'name': '一行更长的文本'
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-40, 30]
},
'properties': {
'image-name': 'popup',
'name': '一行更长的文本'
}
}
]
}
});
map.addLayer({
'id': 'points',
'type': 'symbol',
'source': 'points',
'layout': {
'text-field': ['get', 'name'],
'icon-text-fit': 'both',
'icon-image': ['get', 'image-name'],
'icon-overlap': 'always',
'text-overlap': 'always'
}
});
// 原始的、未拉伸的图像用于比较
map.addSource('original', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [0, -70]
}
}
]
}
});
map.addLayer({
'id': 'original',
'type': 'symbol',
'source': 'original',
'layout': {
'text-field': '未拉伸图像',
'icon-image': 'popup-debug',
'icon-overlap': 'always',
'text-overlap': 'always'
}
});
});
</script>
</body>
</html>