You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Azure Maps实现原生输入自动补全功能?

Azure Maps 原生自动补全实现方案

核心结论

Azure Maps 提供原生的自动补全控件(atlas.AutoComplete),无需依赖第三方UI库即可实现类似Google Maps/Bing Maps的输入补全功能,该控件直接对接Azure Maps搜索服务,支持地址、POI等多种类型的联想建议。

示例代码

HTML 结构

<html>
    <head>
        <!-- 引入Azure Maps主脚本及控件样式 -->
        <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
        <link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" rel="stylesheet" />
    </head>
    <body>
        <!-- 自动补全输入框容器 -->
        <div id="autocomplete-container" style="width: 100%;"></div>
        <p></p>
        <div id="mapControl" style="position: relative;width:100%;min-width:290px;height:500px;"></div>
    </body>
</html>

JavaScript 实现

let map;
const mapCenter = [-73.985130, 40.758896];
const defaultZoom = 15;
const azureKey = "你的Azure Maps订阅密钥";

function initializeMap() {
    map = new atlas.Map('mapControl', {
        center: mapCenter,
        zoom: defaultZoom,
        authOptions: {
            authType: "subscriptionKey",
            subscriptionKey: azureKey
        }
    });

    map.events.add('ready', () => {
        // 创建数据源用于标记选中位置
        const dataSource = new atlas.source.DataSource();
        map.sources.add(dataSource);
        map.layers.add(new atlas.layer.SymbolLayer(dataSource));
        dataSource.add(new atlas.data.Point(mapCenter));

        // 初始化原生自动补全控件
        const autocomplete = new atlas.AutoComplete({
            container: document.getElementById('autocomplete-container'),
            authOptions: {
                authType: "subscriptionKey",
                subscriptionKey: azureKey
            },
            options: {
                minLength: 3, // 触发补全的最小输入长度
                placeholder: "Select a venue",
                countrySet: ["US"], // 限制搜索国家范围
                language: "en-US"
            }
        });

        // 监听选中补全项事件
        autocomplete.events.add('select', (e) => {
            const result = e.result;
            // 更新地图视角到选中位置
            map.setCamera({
                center: [result.position.lon, result.position.lat],
                zoom: defaultZoom
            });
            // 添加标记到地图
            dataSource.add(new atlas.data.Point([result.position.lon, result.position.lat]));
        });
    });
}

// 页面加载完成后初始化地图
window.onload = initializeMap;

关键说明

  • 控件特性:

    • 支持地址、POI的实时联想补全,自动适配输入内容
    • 可配置minLength、countrySet、language等参数缩小搜索范围
    • 内置样式,无需自定义模板即可展示结构化的地址/POI信息;如需自定义展示模板,可通过template参数配置
  • 官方文档参考:

    • 可查阅Azure Maps官方文档中「AutoComplete Control」章节,了解控件的所有配置项、事件及扩展能力
    • 搜索服务相关参数可参考「Search API」文档,调整补全的返回结果类型

内容的提问来源于stack exchange,提问作者Dylan Alcázar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 01:00:18