代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
Label,
SimplePoint,
urlUtils,
} from '@baidumap/mapv-three';
BaiduMapConfig.ak = '您的密钥';
const container = document.getElementById('map');
const aspect = container.clientWidth / container.clientHeight;
const range = aspect < 1 ? 1_930 : 1_480;
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center: [116.42127, 39.9231],
range: (range * 1.82) / Math.min(1.82, aspect),
pitch: 0,
provider: new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
}),
},
rendering: {
enableAnimationLoop: true,
},
});
function station(id, coordinates, properties) {
return {
type: 'Feature',
geometry: {type: 'Point', coordinates},
properties: {id, ...properties},
};
}
const menu = document.getElementById('anchor');
const westStation = [116.417526, 39.922363, 6];
const eastStation = [116.424268, 39.92337, 6];
const subway = urlUtils.getAssetUrl('assets/images/markers/mkr_transit_subway.png');
const textData = GeoJSONDataSource.fromGeoJSON([
station('jinyu', westStation, {text: '金鱼胡同站', textAnchor: menu.value}),
]);
const iconData = GeoJSONDataSource.fromGeoJSON([
station('dengshi', eastStation, {
text: '灯市口站',
icon: subway,
textAnchor: menu.value,
}),
]);
textData.defineAttribute('text').defineAttribute('textAnchor');
iconData.defineAttribute('text').defineAttribute('icon').defineAttribute('textAnchor');
const anchor = engine.add(
new SimplePoint({
color: '#cb5430',
size: 12,
strokeColor: '#fff',
strokeWidth: 2,
depthTest: false,
depthWrite: false,
}),
);
anchor.dataSource = GeoJSONDataSource.fromGeoJSON([station('anchor', westStation, {})]);
const textStyle = {
textSize: 17,
textWeight: '600',
textFillStyle: '#18334a',
textStrokeStyle: '#fff',
textStrokeWidth: 2,
depthTest: false,
depthWrite: false,
};
const textLabel = engine.add(
new Label({
...textStyle,
type: 'text',
// 留出圆点半径及文字描边所需的屏幕空间。
padding: [16, 16],
}),
);
textLabel.dataSource = textData;
const iconLabel = engine.add(
new Label({
...textStyle,
type: 'icontext',
vertexIcons: true,
iconWidth: 30,
iconHeight: 30,
padding: [16, 16],
}),
);
iconLabel.dataSource = iconData;
menu.addEventListener('change', () => {
// textAnchor 指定文字与参考位置对齐的边缘,bottom 使文字显示在上方。
const textAnchor = menu.value;
const centered = textAnchor === 'center';
anchor.visible = !centered;
textData.setAttributeValue('jinyu', 'textAnchor', textAnchor);
iconData.setAttributeValues('dengshi', {
textAnchor,
icon: centered ? '' : subway,
});
engine.requestRender();
});
切换九种文字锚点,观察文字与站点圆点或图标的相对位置。居中时只显示站名,方便观察文字与坐标的对齐。
预览