代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
Text,
} from '@baidumap/mapv-three';
const container = document.getElementById('map');
const center = [116.4223, 39.9189];
const range = (2540 * 1.42) / Math.min(1.42, container.clientWidth / container.clientHeight);
BaiduMapConfig.ak = '您的密钥';
const provider = new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
});
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center,
range,
pitch: 0,
heading: 0,
provider,
},
rendering: {
sky: null,
},
});
function point(coordinates, properties = {}) {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates,
},
properties,
};
}
const stations = [
point([116.422261, 39.914435, 4], {Name: '东单路口西'}),
point([116.426774, 39.914399, 4], {Name: '东单路口东'}),
point([116.417526, 39.922363, 4], {Name: '金鱼胡同'}),
point([116.424268, 39.92337, 4], {Name: '灯市口'}),
];
const source = GeoJSONDataSource.fromGeoJSON(stations);
// 文字内容取自数据的 Name 字段。
source.defineAttribute('text', 'Name');
const text = engine.add(
new Text({
fillStyle: '#18334a',
fontSize: 16,
padding: [4, 4],
strokeStyle: '#ffffff',
lineWidth: 2,
}),
);
text.flat = false;
text.dataSource = source;
// 相互重叠的文字只显示一个。
engine.rendering.collision.add(text, {}, 'text');
为东单至灯市口一带的公交和地铁站标注站名,用 Text 绘制带描边的文字,并开启碰撞检测避免重叠。
预览