Skip to content
目录

小程序使用百度地图POI检索服务和跳转手机导航

第一步:

第二步:

  • 微信公众平台设置请求合法域名

第三步:

第四步:

  • 引入JS模块在项目根目录下新建一个路径,将百度的js文件拷贝到新建的路径下,新建路径 "libs/bmap-wx" ,将 bmap-xw.min.js 文件拷贝至 "libs/bmap-wx" 路径下
js
// 引用百度地图微信小程序JSAPI模块
const bmap = require('./libs/bmap-wx')
let BMap = {}
Page({
  data: {
    markers: [],
    latitude: '',
    longitude: '',
    keywords: ''
  },

  onLoad () {
    this.createMap()
  },

  // 输入搜索
  searchValue(e) {
    this.setData({
      keywords: e.detail
    })
  },

  createMap() {
    // 新建百度地图对象
    BMap = new bmap.BMapWX({ak: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'})
    this.search()
  },

  // 搜索按钮
  search() {
    const fail = data => {
      console.log(data)
      common.showModalCallBack(data)
    }
    const success = data => {
      console.log('🚀 ~ [data]', data)
      if(!data.originalData.results.length) {
        common.showModalCallBack('附近50公里内未找到')
      } else {
        const results = data.originalData.results.map((r, i) => ({
          title: r.name,
          address: r.address,
          id: i,
          mobile: r.telephone,
          detail_info: r.detail_info,
          latitude: r.location.lat,
          longitude: r.location.lng,
          iconPath: 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxx.png'
        }))
        const markers = results.map(marker => ({
          ...marker,
          width: 35,
          height: 45,
          iconPath: 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxx.png'
        }));
        // const mapCtx = wx.createMapContext('map')
        // mapCtx.setLocMarkerIcon({
        //   iconPath:'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png'
        // })
        this.setData({
          markers,
          latitude: results[0].latitude - 0.025,
          longitude: results[0].longitude + 0.01
        });
      }
    }
    // 发起POI检索请求
    BMap.search({
      query: this.data.keywords,
      radius: '50000',
      coord_type: 2,
      center: `${this.data.latitude},${this.data.longitude}`,
      scope: 2,
      filter: 'sort_name:distance|sort_rule:1',
      fail: fail,
      success: success,
    });
  },

  // 点击地址使用手机导航
  navigation(e) {
    const { value } = e.currentTarget.dataset
    wx.openLocation({
      latitude: value.latitude,
      longitude: value.longitude,
      scale: 12,
      name: value.title,
      address: value.address,
    })
  },
})

Released under the MIT License.