代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
DataItem,
DataSource,
Engine,
SimplePoint,
} from '@baidumap/mapv-three';
BaiduMapConfig.ak = '您的密钥';
const container = document.getElementById('map');
const aspect = container.clientWidth / container.clientHeight;
const engine = new Engine(container, {
map: {
center: [120.146, 30.25],
range: 5100 / Math.min(1, aspect),
pitch: 0,
provider: new BaiduVectorTileProvider({
displayOptions: {
poi: false,
},
}),
},
});
const point = engine.add(
new SimplePoint({
size: 16,
vertexColors: true,
depthTest: false,
}),
);
const dataSource = new DataSource({
// 通过构造函数传入属性定义,和 dataSource.defineAttribute 等效。
attributes: {
color: (p) => p.color || '#1267c7',
},
});
dataSource.add([
new DataItem([120.1405, 30.2585]),
new DataItem([120.1573, 30.2459]),
new DataItem([120.148, 30.2378]),
]);
point.dataSource = dataSource;
const colors = ['#d9483b', '#e5a13a', '#3f9e6b', '#8135c1'];
const status = document.getElementById('status');
let count = 3;
// 点击标记点:按 id 修改颜色。
point.addEventListener('click', (e) => {
const color = colors[Math.floor(Math.random() * colors.length)];
dataSource.setAttributeValues(e.entity.value.id, {color});
status.textContent = '已改色,当前 ' + count + ' 个点';
});
// 右击标记点:按 id 删除。
point.addEventListener('rightclick', (e) => {
dataSource.remove(e.entity.value.id);
count--;
status.textContent = '已删除,当前 ' + count + ' 个点';
});
// 点击地图空白处:在点击位置添加一个点。
engine.map.addEventListener('click', (e) => {
if (!e.target) {
dataSource.add(new DataItem(e.point));
count++;
status.textContent = '已添加,当前 ' + count + ' 个点';
}
});
用 DataSource 和 DataItem 管理西湖边的标记点:点击空白处添加点,点击标记点随机改色,右击标记点删除。
预览