代码
import {
  BaiduMapConfig,
  BaiduVectorTileProvider,
  Engine,
  GeoJSONDataSource,
  Label,
  services,
  urlUtils,
} from '@baidumap/mapv-three';

const ak = BaiduMapConfig.ak || '您的密钥';
const hasKey = ak.trim() && !ak.includes('密钥');
if (hasKey) {
  BaiduMapConfig.ak = ak;
}

const provider = hasKey ? new BaiduVectorTileProvider({displayOptions: {poi: false}}) : null;

const engine = new Engine('map', {
  map: {
    projection: 'EPSG:3857',
    center: [116.405, 39.92],
    pitch: 0,
    range: 12_000,
    provider: provider,
  },
});

const form = document.querySelector('#query');
const status = document.querySelector('#status');
if (!hasKey) {
  status.textContent = '配置百度地图 AK 后可查询。';
}

const keyword = document.querySelector('#keyword');
const submit = document.querySelector('#submit');
const results = document.querySelector('#results');

const search = new services.LocalSearch({
  apiSource: services.API_SOURCE_BAIDU,
  pageCapacity: 5,
  renderOptions: {
    engine,
    enableRender: false,
  },
});

const marker = engine.add(
  new Label({
    type: 'icontext',
    vertexIcons: true,
    iconWidth: 20,
    iconHeight: 31,
    textAnchor: 'left',
    textSize: 13,
    textWeight: '600',
    textFillStyle: '#18334a',
    textStrokeStyle: '#ffffff',
    textStrokeWidth: 3,
    padding: [5, 4],
    pixelOffset: [0, 14],
    depthTest: false,
    depthWrite: false,
  }),
);

function showLabels(points) {
  marker.visible = points.length > 0;
  if (points.length) {
    const source = GeoJSONDataSource.fromGeoJSON(
      points.map(({point, text, icon}) => ({
        type: 'Feature',
        geometry: {type: 'Point', coordinates: [...point, 5]},
        properties: {text: shortText(text), icon},
      })),
    );
    source.defineAttribute('text').defineAttribute('icon');
    marker.dataSource = source;
  }
  engine.requestRender();
}

function shortText(text) {
  const chars = Array.from(text);
  return chars.length > 14 ? chars.slice(0, 13).join('') + '…' : text;
}

function pointArray(point) {
  const values = Array.isArray(point) ? point : [point?.x, point?.y];
  const [lng, lat] = values;
  return Number.isFinite(lng) && Number.isFinite(lat) ? [lng, lat] : null;
}

async function withTimeout(promise) {
  let timer;
  const timeout = new Promise((resolve, reject) => {
    timer = setTimeout(() => reject(new Error('请求超时')), 12_000);
  });
  try {
    return await Promise.race([promise, timeout]);
  } finally {
    clearTimeout(timer);
  }
}

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  if (!hasKey) {
    status.textContent = '配置百度地图 AK 后可查询。';
    return;
  }

  const value = keyword.value.trim();
  if (!value) {
    status.textContent = '请输入检索关键字。';
    return;
  }

  submit.disabled = true;
  status.textContent = '正在检索地点…';
  results.replaceChildren();
  showLabels([]);

  try {
    const response = await withTimeout(
      search.search(value, {
        forceLocal: true,
      }),
    );
    const places = response?.pois ?? [];
    if (places.length === 0) {
      status.textContent = '未返回地点。请更换关键字,或检查地图 AK 的服务权限。';
      return;
    }

    const labels = [];
    for (const [index, place] of places.entries()) {
      const item = document.createElement('li');
      const title = [place.title, place.address].filter(Boolean).join(' · ');
      const point = pointArray(place.point);
      if (point) {
        labels.push({
          point,
          text: place.title || place.address || `地点 ${index + 1}`,
          icon: urlUtils.getAssetUrl(`assets/images/markers/mkr_red_${index + 1}.png`),
        });
        const button = document.createElement('button');
        button.type = 'button';
        button.textContent = title;
        button.addEventListener('click', () => {
          engine.map.lookAt(point, {
            range: 1_500,
            pitch: 0,
          });
        });
        item.append(button);
      } else {
        item.textContent = title;
      }
      results.append(item);
    }

    showLabels(labels);
    const points = labels.map(({point}) => point);
    if (points.length > 1) {
      engine.map.setViewport(points, {
        zoom: -1,
        range: 2_000,
      });
      const panel = form.closest('.operate');
      const {width, height} = engine.renderer.domElement.getBoundingClientRect();
      if (panel.getBoundingClientRect().width > width * 0.75) {
        // 窄屏结果面板占据视口上部,将检索点整体移到面板下方。
        const map = engine.map;
        const center = map.projectArrayCoordinate(map.getCenter());
        const pixels = Math.min(panel.getBoundingClientRect().bottom / 2, height * 0.2);
        center[1] += pixels * map.getZoomUnits();
        map.lookAt(map.unprojectArrayCoordinate(center), {range: map.getRange(), pitch: 0});
      }
    } else if (points.length === 1) {
      engine.map.lookAt(points[0], {
        range: 1_500,
        pitch: 0,
      });
    }

    status.textContent = `当前页 ${places.length} 个地点。`;
  } catch {
    status.textContent = '地点检索失败,请检查网络及 AK 的服务权限。';
  } finally {
    submit.disabled = false;
  }
});

调用 services.LocalSearch.search 按关键字查找地点,以当前地图中心所在城市为检索区域。列表展示首页结果,点击地点可定位并在地图上保留检索点。 缺少密钥时可浏览 OpenFreeMap 预览底图。 用编号图标和地点名称标注当前页的检索结果。

预览