關於小程序中地圖的應用(聯動搜索,模糊查詢,定位導航)

一、獲取微信地址

  • 在小程序的開發中,內置了獲取微信地址的API接口。我們可以直接調用,對返回的數據進行相關的處理即可。代碼如下:
    <view class="wx_address flex_c_m" bindtap='weChat'>
      <text class="iconfont iconweixin1"></text>
      <text class="we_address">獲取微信收貨地址</text>
    </view>
  // 獲取微信地址
  weChat() {
    let that = this;
    wx.getSetting({
      success(res) {
        console.log("vres.authSetting['scope.address']:", res.authSetting['scope.address'])
        if (res.authSetting['scope.address']) {
          wx.chooseAddress({
            success(res) {
              console.log(res.userName)
              console.log(res.postalCode)
              console.log(res.provinceName)
              console.log(res.provinceName)
              console.log(res.countyName)
              console.log(res.detailInfo)
              console.log(res.nationalCode)
              console.log(res.telNumber)
              let obj = {
                TakeMan: res.userName,
                TakeTel: res.telNumber,
                TakeProvince: res.provinceName,
                TakeCity: res.cityName,
                TakeArea: res.countyName,
                TakeAddress: res.detailInfo,
                TakeBuildingNo: "",
                IsDefault: false,
                CommunityName: "",
                CommunityAddress: "",
                TakeLongitude: "",
                TakeLatitude: ""
              }
              http.requestLoading('api/services/app/ShopMemerShippingAddressService/AddMemerShippingAddress', obj, '', 'POST').then(res => {
                console.log(res)
                if (res.data.Result.Code == 0) {
                  wx.showToast({
                    title: '獲取微信地址成功',
                    icon: 'none'
                  })
                  that.getAddressList();
                }
              })
            }
          })
          // 用戶已經同意小程序使用錄音功能,後續調用 wx.startRecord 接口不會彈窗詢問
        } else {
          if (res.authSetting['scope.address'] == false) {
            wx.openSetting({
              success(res) {
                console.log(res.authSetting)
              }
            })
          } else {
            wx.chooseAddress({
              success(res) {
                console.log(res.userName)
                console.log(res.postalCode)
                console.log(res.provinceName)
                console.log(res.cityName)
                console.log(res.countyName)
                console.log(res.detailInfo)
                console.log(res.nationalCode)
                console.log(res.telNumber)
                // that.setData({
                //   userName: res.userName,
                //   provinceName: res.provinceName,
                //   cityName: res.cityName, //第二級地址
                //   countyName: res.countyName, //第三級地址
                //   detailInfo: res.detailInfo, //詳細收貨地址信息
                //   telNumber: res.telNumber //收貨人手機號碼
                // })
              }
            })
          }
        }
      }
    })
  }
  • 效果圖如下:
    在這裏插入圖片描述

二、聯動搜索及模糊查詢

  • 在項目中實現選擇省市區,根據選擇的內容進行更詳細的地址。詳細地址可以通過搜索查到,具體代碼如下:
    <view class="address_top">
      <view class="wx_address flex_c_m" bindtap='weChat'>
        <text class="iconfont iconweixin1"></text>
        <text class="we_address">獲取微信收貨地址</text>
      </view>
      <view class="personal">
        <view class="personal_list">
          <view class="personal_data">
            <text class="personal_data_type">收貨人</text>
            <input class="zc_input" bindinput="inputValue" value="{{userName}}" placeholder="請填寫收貨人姓名"></input>
          </view>
        </view>
        <view class="personal_list">
          <view class="personal_data">
            <text class="personal_data_type">手機號碼</text>
            <input class="zc_input" bindinput="telNumber" value="{{telNumber}}" placeholder="請填寫聯繫方式"></input>
          </view>
        </view>
        <view class="personal_list">
          <picker mode="region" bindchange="bindRegionChange" value="{{region}}">
            <view class="personal_data">
              <text class="personal_data_type">所在地址</text>
              <view class="picker">
                <text class="address">{{region.length ? (region[0]+'-'+region[1]+'-'+region[2]) : ''}}</text>
                <text class="iconfont iconxiangshang-copy toushustore_right"></text>
              </view>
            </view>
          </picker>
        </view>
        <view class="personal_list">
          <view class="personal_data" bindtap='onChangeAddress'>
            <text class="personal_data_type">詳細地址</text>
            <input class="zc_input_txt" placeholder="請輸入所在小區/大廈/學校 等" value="{{chooseAddress}}"></input>
            <text class="iconfont iconxiangshang-copy toushustore_right"></text>
          </view>
        </view>
        <view class="personal_list">
          <view class="personal_data">
            <text class="personal_data_type">樓牌號</text>
            <input class="zc_input_txt" value="{{IDNo}}" maxlength="18" placeholder="請輸入樓號/門牌號" bindinput="idNo"></input>
          </view>
        </view>
      </view>
    </view>
    <view style="height:30rpx;"></view>
    <view class="switch flex_lr_m">
      <view>設爲默認地址</view>
      <view>
        <switch checked="{{switch1Checked}}" bindchange="switch1Change" color="#FEB1C6" />
      </view>
    </view>
    <!-- 保存收貨地址 -->
    <view class="add_address flex_c_m" bindtap="Preservation">
      <text class="add_txt">保存</text>
    </view>
  • 這裏需要說明一下,需要引入騰訊地圖的SDK。藉助SDK實現將省市區轉爲經緯度,從而實現聯動的效果。模糊查詢是藉助內置的API實現的。
// pages/shoppingMall/Addaddress/Addaddress.js
const http = require('../../../server/request.js');
const QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
const app = require('../../../utils/uselogn.js'); //獲取應用實例
// 引入SDK核心類
// 實例化API核心類
let qqMap = new QQMapWX({
  key: 'PIQBZ-VC6L5-6MRIU-QXQJE-BOVHK' // 必填
});
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    userName: '', //收貨人姓名
    provinceName: '', //國標收貨地址第一級地址
    cityName: '', //國標收貨地址第二級地址
    countyName: '', //國標收貨地址第三級地址
    detailInfo: '', //詳細收貨地址信息
    telNumber: '', //收貨人手機號碼
    region: [],
    switch1Checked: false,
    chooseAddress: '',
    IDNo: '',
    lng: '',
    lat: '',
    isshop: true, //判斷來源
    i:''
  },
  onLogin: app.userLogin,
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function(options) {
    console.log(options)
    if (Object.keys(options).length == 0) {
      console.log("空對象")
    } else {
      console.log("非空對象")
      this.setData({
        isshop: false,
        i: options.index
      })
    }
  },

  /**
   * 生命週期函數--監聽頁面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命週期函數--監聽頁面顯示
   */
  onShow: function() {
    this.onLogin(this.authCallback);
  },
  authCallback: function() {

  },
  /**
   * 生命週期函數--監聽頁面隱藏
   */
  onHide: function() {

  },

  /**
   * 生命週期函數--監聽頁面卸載
   */
  onUnload: function() {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function() {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function() {

  },
  // 獲取微信地址
  weChat() {
    let that = this;
    wx.getSetting({
      success(res) {
        console.log("vres.authSetting['scope.address']:", res.authSetting['scope.address'])
        if (res.authSetting['scope.address']) {
          wx.chooseAddress({
            success(res) {
              console.log(res.userName)
              console.log(res.postalCode)
              console.log(res.provinceName)
              console.log(res.provinceName)
              console.log(res.countyName)
              console.log(res.detailInfo)
              console.log(res.nationalCode)
              console.log(res.telNumber)
              let region = [];
              region.push(res.provinceName, res.countyName, res.countyName)
              that.setData({
                userName: res.userName,
                telNumber: res.telNumber, //收貨人手機號碼
                region: region,
                chooseAddress: res.detailInfo
              })
            }
          })
          // 用戶已經同意小程序使用錄音功能,後續調用 wx.startRecord 接口不會彈窗詢問
        } else {
          if (res.authSetting['scope.address'] == false) {
            wx.openSetting({
              success(res) {
                console.log(res.authSetting)
              }
            })
          } else {
            wx.chooseAddress({
              success(res) {
                console.log(res.userName)
                console.log(res.postalCode)
                console.log(res.provinceName)
                console.log(res.cityName)
                console.log(res.countyName)
                console.log(res.detailInfo)
                console.log(res.nationalCode)
                console.log(res.telNumber)
              }
            })
          }
        }
      }
    })
  },
  //地區選擇
  bindRegionChange: function(e) {
    console.log('picker發送選擇改變,攜帶值爲', e)
    this.setData({
      region: e.detail.value
    })
    console.log(e.detail.value[0] + e.detail.value[1] + e.detail.value[2])
    qqMap.geocoder({
      address: e.detail.value[0] + e.detail.value[1] + e.detail.value[2],
      complete: (res => {
        console.log(res.result.location); //經緯度對象
        this.setData({
          lng: res.result.location.lng,
          lat: res.result.location.lat
        })
      })
    })
  },
  // 是否默認
  switch1Change(e) {
    console.log(e)
    this.setData({
      switch1Checked: e.detail.value
    })
  },
  // 保存收貨地址
  Preservation() {
    let parm = {
      TakeMan: this.data.userName,
      TakeTel: this.data.telNumber,
      TakeProvince: this.data.region[0],
      TakeCity: this.data.region[1],
      TakeArea: this.data.region[2],
      TakeAddress: this.data.chooseAddress,
      TakeBuildingNo: this.data.IDNo,
      IsDefault: this.data.switch1Checked,
      CommunityName: "",
      CommunityAddress: "",
      TakeLongitude: "",
      TakeLatitude: ""
    }
    console.log(parm)
    http.requestLoading('api/services/app/ShopMemerShippingAddressService/AddMemerShippingAddress?__shop__=4aa5b012-65aa-4f1c-be1f-c7c5852dee7b', parm, '', 'POST').then(res => {
      console.log(res)
      if (res.data.Result.Code == 0) {
        wx.showToast({
          title: '地址保存成功',
          icon: 'none'
        })
        if (this.data.i == 1) {
          wx.setStorageSync('addreass', parm)
          wx.navigateBack({
            delta: 2
          })
        } else if (this.data.i == 2) {
          wx.setStorageSync('addreass1', parm)
          wx.navigateBack({
            delta: 2
          })
        } else {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/shoppingMall/shippingAddress/shippingAddress',
            })
          }, 500)
        }
      }
    })
  },
  //移動選點
  onChangeAddress: function() {
    var _page = this;
    wx.chooseLocation({
      latitude: _page.data.lat,
      longitude: _page.data.lng,
      success: function(res) {
        _page.setData({
          chooseAddress: res.name
        });
      },
      fail: function(err) {
        console.log(err)
      }
    });
  },
  // 樓牌號
  idNo(e) {
    console.log(e.detail.value)
    this.setData({
      IDNo: e.detail.value
    })
  },
  // 收貨人
  inputValue(e) {
    this.setData({
      userName: e.detail.value
    })
  },
  // 手機號
  telNumber(e) {
    this.setData({
      telNumber: e.detail.value
    })
  }
})
  • 效果圖如下所示:
    在這裏插入圖片描述在這裏插入圖片描述

三、導航

  • 導航可以利用小程序自帶的API去實現,通過傳遞不同的參數來控制目的地不同。代碼如下:
    <view class="receiv flex_lr_m" bindtap="click">
      <text class="receiv_name">提貨地點</text>
      <view class="dib receiv_address">{{shoplists.StoreAddress}}</view>
      <text class="iconfont icondizhi1"></text>
    </view>
  // 導航
  click() {
    console.log(1)
    let that = this;
    let lat = that.data.shoplists.Latitude;
    let long = that.data.shoplists.Longitude;
    wx.getLocation({ //獲取當前經緯度
      type: 'wgs84', //返回可以用於wx.openLocation的經緯度,官方提示bug: iOS 6.3.30 type 參數不生效,只會返回 wgs84 類型的座標信息  
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        console.log(typeof latitude, longitude, res, typeof lat, parseFloat(long))
        wx.openLocation({ //​使用微信內置地圖查看位置。
          latitude: latitude, //要去的緯度-地址
          longitude: longitude, //要去的經度-地址
          name: that.data.shoplists.StoreAddress,
          address: that.data.shoplists.StoreAddress
        })
      }
    })
  }
  • 效果圖如下:
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章