代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
Popup,
SimplePoint,
} from '@baidumap/mapv-three';
const container = document.getElementById('map');
const center = [116.404716, 39.912747];
const range = (850 * 1.42) / Math.min(1.42, container.clientWidth / container.clientHeight);
BaiduMapConfig.ak = '您的密钥';
const provider = new BaiduVectorTileProvider({
displayOptions: {
building: false,
},
});
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center,
range,
pitch: 16,
heading: 0,
provider,
},
rendering: {
sky: null,
enableAnimationLoop: true,
},
});
function point(coordinates, properties = {}) {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates,
},
properties,
};
}
const stations = [
{
coordinates: [116.402966, 39.912047, 4],
name: '西站',
hours: '07:30 – 19:30',
},
{
coordinates: [116.406566, 39.913247, 4],
name: '东站',
hours: '08:00 – 21:00',
},
];
const source = GeoJSONDataSource.fromGeoJSON(
stations.map((station, index) =>
point(station.coordinates, {
stationIndex: index,
}),
),
);
source.defineAttribute('stationIndex');
const dots = engine.add(
new SimplePoint({
depthTest: false,
size: 23,
color: '#198982',
}),
);
dots.dataSource = source;
const content = document.createElement('span');
const status = document.getElementById('status');
const popup = engine.add(
new Popup({
point: stations[0].coordinates,
offset: [0, -16],
className: 'station-popup',
title: stations[0].name,
content,
}),
);
popup.stopPropagation = true;
function openStation(station) {
// 更新同一个窗口的坐标、标题和内容。
popup.point = station.coordinates;
popup.title = station.name;
content.textContent = '服务时间 ' + station.hours;
popup.visible = true;
status.textContent = station.name + '信息已打开';
engine.requestRender();
}
popup.addEventListener('close', () => {
status.textContent = '信息窗口已关闭';
});
dots.addEventListener('click', ({entity}) => {
const station = stations[entity?.pairs.stationIndex];
if (station) openStation(station);
});
document.getElementById('west').addEventListener('click', () => openStation(stations[0]));
document.getElementById('east').addEventListener('click', () => openStation(stations[1]));
openStation(stations[0]);
通过 Popup 的 point、title、content 和 visible 更新同一个信息窗口。可点击站点打开,也可关闭后通过按钮重新打开。 使用北京前门一带的百度矢量地图,覆盖物数据用于演示。
预览