1、动态引入高德地图api
const script = document.createElement('script'); script.src = `https://webapi.amap.com/maps?v=2.0&key=${config.amap_key}&plugin=AMap.Adaptor`; document.body.appendChild(script);
2、搜索地址方法
search() { if (this.searchText && this.map) { const that = this; (window as any).AMap.plugin(['AMap.PlaceSearch'], (res) => { const placeSearch = new (window as any).AMap.PlaceSearch({ pageSize: 5, // 单页显示结果条数 pageIndex: 1, // 页码 map: that.map, // 展现结果的地图实例 panel: 'map_address_search_container', // 结果列表将在此容器中进行展示。 autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围 }); placeSearch.search(that.searchText, function (status, result) { console.log(status, result); }); }); } }
这样写过以后本以为就可以,但是搜索并没效果,placeSearch.search 一直为error 状态
最后查到需将高德地图secretKey放在全局环境变量(window) 的_AMapSecurityConfig中,因此在1步骤后增加
(window as any)._AMapSecurityConfig = {
securityJsCode: config.secret_key,
};
这样写过以后问题解决