先附上实现效果:
  

实现的功能有:(中间“红色图标”所在位置为选择的定位)
1. 拖动地图,进行定位;
2. 根据输入的内容进行地图定位。

一. 申请秘钥ak ,下载百度地图微信小程序JavaScript API

1. 百度地图开放平台申请ak:http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5

注册 -> 登录 -> 控制台 ->创建应用

创建应用时,应用名称自定义,应用类型选择“微信小程序”,APPID为小程序的appId,然后提交。

复制AK即可。


2. 下载百度地图微信小程序JavaScript API:http://lbsyun.baidu.com/index.php?title=wxjsapi/wxjs-download

下载后,拷贝到libs目录下,在相应js模块进行引入。

二. map.wxml

先展示map.wxml

<view class='map'>
  <!-- 搜索框 -->
  <view class='search pRelative'>
    <icon class='iconfont icon-icon--'></icon>
    <input type='text' placeholder='搜索' bindinput="bindKeyInput" value='{{searchCon}}'></input>
  </view>
  <view class='section'>
    <!-- 地图 -->
    <map id="myMap" 
    latitude="{{latitude}}" 
    longitude="{{longitude}}" 
    scale="{{scale}}" 
    markers="{{markers}}" 
    covers="{{covers}}" 
    bindcontroltap="controltap"
    bindmarkertap="markertap"
    bindregionchange="regionchange"
    show-location >
    <!-- 搜索列表 -->
    <cover-view class="searchCon">
      <cover-view class='searchCon-item' wx:for="{{searchResult}}" wx:key="unique" data-value="{{item}}" bindtap='tapSearchResult'>
        <cover-view class='iconfont icon-icon--'></cover-view>
        <cover-view class='addressname'>
          {{item.name}}
          <cover-view>{{item.province+item.city+item.district}}</cover-view>
        </cover-view>
      </cover-view>     
    </cover-view>  
    <!-- 中间红色图标 -->
    <cover-view class='mapPic'>
      <cover-image src='../../../../public/image/location.png'></cover-image>
    </cover-view>
    </map>
  </view>
  <!-- 获取的地址信息 -->
  <view class='footer'>
    <view>
      <text>地址:</text>
      <text>{{address}}</text>
    </view>
    <view>
      <text>经度:</text>
      <text>{{longitude}}</text>
    </view>
    <view>
      <text>纬度:</text>
      <text>{{latitude}}</text>
    </view>
  </view>
</view>

搜索框中的搜索图标是阿里巴巴矢量图标库中下载:https://www.iconfont.cn/

下载后,将文件拷贝到public目录下,并在app.wxss中引入,即可全局使用。

三. js实现 -- 拖动地图,进行定位

1. 封装的wx.getLocation放在app.js中,供全局使用,使用方式:app.getLocation()。

 //获取地理位置
  getLocation: function (successCallback) {
    let that = this;
    wx.getLocation({
      //默认wgs84
      type: 'gcj02',
      success: function (location) {
        if (successCallback) {
          successCallback(location);
        }
      },
      fail: function () {
        that.showModal({
          title: '',
          content: '请允许获取您的定位',
          confirmText: '授权',
          success: function (res) {
            if (res.confirm) {
              that.openSetting();
            } else {

            }
          }
        })
      }
    })
  },

 2. 初始化页面,执行onLoad()方法,实例化百度地图API核心类,微信小程序获取当前位置经纬度。

/**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    const that = this;
    // 实例化百度地图API核心类
    bmap = new BMap.BMapWX({
      ak: app.globalData.ak
    })
    //获取当前位置经纬度
    app.getLocation(function (location) {
      console.log(location);
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      that.setData({
        longitude: location.longitude,
        latitude: location.latitude,
        [str]: location.longitude,
        [str2]: location.latitude,
      })
    })
  },

 3. 每当地图视野变化时,会执行regionchange(),中间红色图标为当前定位。

// markets
  getLngLat(){
    var that = this; 
    this.mapCtx = wx.createMapContext("myMap"); 
    var latitude, longitude;
    this.mapCtx.getCenterLocation({ 
      success: function (res) { 
        latitude = res.latitude;
        longitude = res.longitude;
        var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
        that.setData({ 
          longitude: res.longitude, 
          latitude: res.latitude, 
          [str]: res.longitude,
          [str2]: res.latitude,
        })
        that.regeocoding(); //根据经纬度-》解析地址名称 
      } 
    })

    //修改坐标位置 
    this.mapCtx.translateMarker({
      markerId: 1,
      autoRotate: true,
      duration: 1000,
      destination: {
        latitude: latitude,
        longitude: longitude,
      },
      animationEnd() {
        console.log('animation end')
      }
    })
  },
  //地图视野变化触发的事件
  regionchange(e) {
    // 地图发生变化的时候,获取中间点,也就是用户选择的位置
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      this.getLngLat();
    }
  },

 

为了实现红色图标在视觉上是固定在中间。因此我在map.wxml(具体代码如上)中,通过cover-image标签,引入红色图标,然后position定位在中间。

<cover-view class='mapPic'>
   <cover-image src='../../../../public/image/location.png'></cover-image>
</cover-view>

然后js部分data数据中的markers参数进行设置,将其width和height的值设置为1,不要设置0,适得其反(当然可以试一下是什么情况)。

data: {
    searchCon:'',//输入内容
    searchResult:[],//搜索列表

    longitude:'',//经度
    latitude:'',//纬度
    address: '',
    scale: 16,//地图的扩大倍数
    markers: [{ //标记点用于在地图上显示标记的位置
      id: 1,
      latitude: '',
      longitude: '',
      iconPath: '../../../../public/image/location.png',
      width: 1,
      height: 1,
    }],
  },

4. 逆地址解析 -- 从经纬度转换为地址信息。

// 发起regeocoding逆地址解析 -- 从经纬度转换为地址信息
  regeocoding(){
    const that = this;
    bmap.regeocoding({
      location:that.data.latitude+','+that.data.longitude,
      success: function(res){
        that.setData({
          address: res.wxMarkerData[0].address
        })
      },
      fail: function(res){
        that.tipsModal('请开启位置服务权限并重试!')
      },
      
    });
  },

四. js实现 -- 根据输入的内容进行地图定位

1. 每输入一个字符,便会进行搜索。其中 tapSearchResult()方法是点击显示的搜索列表某一项所触发的。

// 绑定input输入 --搜索
  bindKeyInput(e){
    var that = this; 
    var fail = function (data) { //请求失败
      console.log(data) 
    };
    var success = function (data) { //请求成功
      var searchResult =[];
      for(var i=0;i<data.result.length;i++){ //搜索列表只显示10条
        if(i>10){ 
          return;
        }
        if (data.result[i].location){
          searchResult.push(data.result[i]);
        }
      }
      that.setData({
        searchResult: searchResult
      });
    }
    // 发起suggestion检索请求 --模糊查询
    bmap.suggestion({
      query: e.detail.value,
      city_limit: false,
      fail: fail,
      success: success
    });
  },
  // 点击搜索列表某一项
  tapSearchResult(e){
    var that = this;
    var value=e.currentTarget.dataset.value;
    var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
    that.setData({
      longitude: value.location.lng,
      latitude: value.location.lat,
      searchResult:[],
      searchCon: value.name,
      address: value.province+value.city + value.district+value.name,
      [str]: value.location.lng,
      [str2]: value.location.lat,
    })
  },

效果如下:

五. 全部map.js代码

// pages/map/map.js
const app = getApp();
// 引用百度地图微信小程序JSAPI模块
const BMap = require('../../libs/bmap-wx.min.js');
var bmap;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchCon:'',//输入内容
    searchResult:[],//搜索列表

    longitude:'',//经度
    latitude:'',//纬度
    address: '',
    scale: 16,//地图的扩大倍数
    markers: [{ //标记点用于在地图上显示标记的位置
      id: 1,
      latitude: '',
      longitude: '',
      iconPath: '../../../../public/image/location.png',
      width: 1,
      height: 1,
    }],
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    const that = this;

    // 实例化百度地图API核心类
    bmap = new BMap.BMapWX({
      ak: app.globalData.ak
    })

    //获取当前位置经纬度
    app.getLocation(function (location) {
      console.log(location);
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      that.setData({
        longitude: location.longitude,
        latitude: location.latitude,
        [str]: location.longitude,
        [str2]: location.latitude,
      })
    })
  },
  // 绑定input输入 --搜索
  bindKeyInput(e){
    var that = this; 
    var fail = function (data) { //请求失败
      console.log(data) 
    };
    var success = function (data) { //请求成功
      var searchResult =[];
      for(var i=0;i<data.result.length;i++){ //搜索列表只显示10条
        if(i>10){ 
          return;
        }
        if (data.result[i].location){
          searchResult.push(data.result[i]);
        }
      }
      that.setData({
        searchResult: searchResult
      });
    }
    // 发起suggestion检索请求 --模糊查询
    bmap.suggestion({
      query: e.detail.value,
      city_limit: false,
      fail: fail,
      success: success
    });
  },
  // 点击搜索列表某一项
  tapSearchResult(e){
    var that = this;
    var value=e.currentTarget.dataset.value;
    var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
    that.setData({
      longitude: value.location.lng,
      latitude: value.location.lat,
      searchResult:[],
      searchCon: value.name,
      address: value.province+value.city + value.district+value.name,
      [str]: value.location.lng,
      [str2]: value.location.lat,
    })
  },
  // markets
  getLngLat(){
    var that = this; 
    this.mapCtx = wx.createMapContext("myMap"); 
    var latitude, longitude;
    this.mapCtx.getCenterLocation({ 
      success: function (res) { 
        latitude = res.latitude;
        longitude = res.longitude;
        var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
        that.setData({ 
          longitude: res.longitude, 
          latitude: res.latitude, 
          [str]: res.longitude,
          [str2]: res.latitude,
        })
        that.regeocoding(); //根据经纬度-》解析地址名称 
      } 
    })

    //修改坐标位置 
    this.mapCtx.translateMarker({
      markerId: 1,
      autoRotate: true,
      duration: 1000,
      destination: {
        latitude: latitude,
        longitude: longitude,
      },
      animationEnd() {
        console.log('animation end')
      }
    })
  },
  //地图位置发生变化
  regionchange(e) {
    // 地图发生变化的时候,获取中间点,也就是用户选择的位置
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      this.getLngLat();
    }
  },
  markertap(e) {
    console.log(e.markerId)
    console.log(e);
  },
  controltap(e) {
    console.log(e.controlId)
  },

  // 发起regeocoding逆地址解析 -- 从经纬度转换为地址信息
  regeocoding(){
    const that = this;
    bmap.regeocoding({
      location:that.data.latitude+','+that.data.longitude,
      success: function(res){
        that.setData({
          address: res.wxMarkerData[0].address
        })
      },
      fail: function(res){
        that.tipsModal('请开启位置服务权限并重试!')
      },
      
    });
  },
  //提示
  tipsModal: function (msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      confirmColor: '#2FB385'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

六.解决报错问题

61. message: "APP Referer校验失败"
      status: 220

解决:请确认百度地图创建的应用中填写的APP ID与当前项目的appID是否一致!

 

 

github代码下载:https://github.com/MaiEmily/map

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐