search 用于检索中心点周边的 POI 信息,快速回答"我周围有什么"。不传 location 时以当前定位点为中心。
返回结果包含两部分:wxMarkerData 是符合小程序 marker 规范的数组,可直接用于 <map> 组件;originalData 是 Place API 返回的完整原始数据,方便自定义开发。
其余参数与地点检索请求参数一致,会原样透传。
success 回调入参:
wxMarkerData 数组元素字段:
返回的 marker 元素会原样透传调用方传入的样式字段(iconPath / iconTapPath / width / height / alpha),因此可直接绑定到 小程序 map 组件 的 markers 属性。
失败时走 fail 回调,入参统一为 { errMsg, message, statusCode, rawMessage },字段含义见"服务介绍 → 统一的回调约定"。
以当前定位点为中心检索周边酒店,把结果标注到地图上,点击标注展示详情:
// pages/index/index.js// 引用百度地图微信小程序 JSAPI 模块const { BMapWX } = require('../../libs/bmap-wx.min.js');const bmap = new BMapWX({ ak: '您的ak' });Page({data: {latitude: '',longitude: '',markers: [],pois: [],placeData: null,error: '',},onLoad() {// 不传 location 时以当前定位点为中心bmap.search({query: '酒店',iconPath: '../../img/marker_red.png',iconTapPath: '../../img/marker_red.png',success: (res) => {const list = res.wxMarkerData;if (!list.length) {this.setData({ error: '周边没有检索到相关地点' });return;}this.setData({markers: list,pois: list,latitude: list[0].latitude,longitude: list[0].longitude,});},fail: err => this.setData({ error: '检索失败:' + (err.message || err.errMsg) }),});},onMarkerTap(e) {const poi = this.data.pois[e.markerId];if (!poi) { return; }this.setData({placeData: {title: poi.title,address: poi.address || '暂无',telephone: poi.telephone || '暂无',},});},});
<!-- pages/index/index.wxml --><mapstyle="width: 100%; height: 300px;"longitude="{{longitude}}"latitude="{{latitude}}"scale="14"show-locationmarkers="{{markers}}"bindmarkertap="onMarkerTap"/><view wx:if="{{placeData}}"><text>名称:{{placeData.title}}</text><text>地址:{{placeData.address}}</text><text>电话:{{placeData.telephone}}</text></view><view wx:if="{{error}}">{{error}}</view>
下图为官方 Demo"周边检索"的运行界面,扫描下方小程序码即可直接体验。Demo 是产品化示例,界面比上面的示例代码精致,但调用方式与返回数据完全一致。


切换选中项时如果整组替换 markers,小程序会销毁并重建全部 marker 图层,视觉上表现为闪烁。改为按路径只更新变化的字段可以避免:
// pages/index/index.jsPage({// 点击 marker 时高亮选中项:只更新变化的 iconPath 路径,// 不整组替换 markers,避免地图图层重建导致闪烁onMarkerTap(e) {const id = e.markerId;const patch = {};this.data.markers.forEach((m, i) => {const target = i === id ? '../../img/marker_yellow.png' : '../../img/marker_red.png';if (m.iconPath !== target) {patch['markers[' + i + '].iconPath'] = target;}});this.setData(patch);},});
示例中的 marker 图标需自行放到 img 目录下,可从开发包 demo/img/ 获取;未传 iconPath 时使用小程序默认标注样式。
未显式传 location 时会调用 wx.getLocation,请先在 app.json 中声明 getLocation 隐私接口,见配置环境。
检索结果条数受 page_size 与关键词覆盖度影响,query 越具体结果越准确。
上一篇
下一篇