欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

小程序接入腾讯地图(定位、搜索、计算距离)

最编程 2024-03-04 08:29:55
...

这是一个小程序接入腾讯地图的案例,涉及了腾讯地图sdk的地点搜索、模糊查询、定位当前位置、计算两点之间的距离,如下图。不多说,直接上码。


TIM图片20190411135534.png
TIM图片20190411135618.png
TIM图片20190411135655.png
<view class="app">

  <view class='map' style="width:100%;height:{{windowHeight}}px;">
    <view class='form pad'>
      <form  bindsubmit='formSubmit' >
        <view class='label'>
          <view class='label-i'>{{thisCity.city}}</view>
          <image src='/imgs/icon-search.png' mode='widthFix' />
          <input value='{{inputVal}}' bindinput="getsuggest" name="site" placeholder='小区、写字楼、学校 等' />
        </view>
        <view class='search-bind'>
          <button type='button' formType='submit'>提交</button>
        </view>
      </form>
    </view>


    <!-- 关键词 -->
    <view class='vague' wx:if="{{vague.length>0}}">
      <view wx:for="{{vague}}" wx:key="{{index}}" data-name='{{item.title}}' data-data='{{item.data}}' formType='submit' bindtap='bindSearch'>{{item.title}}</view>
    </view>

    <!-- 返回的地址 -->
    <view class='list pad {{index == listIndex?"active":""}}' wx:if="{{siteData.length>0}}">
      <view class='list-li' wx:for="{{siteData}}" wx:key="{{index}}" data-location='{{item.location}}' data-index='{{index+1}}' bindtap='bindDistance'>
        <view class='list-img'>
          <image src='{{item.checked?"/imgs/icon23.png":"/imgs/icon22.png"}}' mode='widthFix'/>
        </view>
        <view class='list-r'>
          <view class='list-p'>{{item.title}}</view>
          <view class='list-span text-truncate2'>{{item.address}}</view>
        </view>
        <view class='bindBtn' wx:if="{{item.scope}}"  bindtap='bindBtn'>确认地址</view>
      </view>
    </view>

    <view class='map-box {{siteData.length>0?"active":""}} {{vague.length>0?"hide":""}}'  style="width:{{windowWidth}}px;height:{{windowHeight}}px;">
      <map id="myMap"
      markers="{{markers}}"
      style="width:100%;height:100%;"
      scale='{{scale}}' latitude='{{latitude}}' longitude='{{longitude}}' show-location>
    </map>
    </view>
  </view>
</view>
.map{
  position: relative;
}

.form{
  width: 100%;
  height: 110rpx;
  background: #17b356;
  z-index: 100;
  padding: 15rpx 20rpx ;
  position: fixed;
  top: 0;
  left: 0;
}
.form form{
  width: 100%;
  height: 80rpx;
  overflow: hidden;
  display: block;
  position: relative;
}
.label{
  width:610rpx;
  height: 80rpx;
  position: relative;
  background: #fff;
  border-radius: 6rpx;
  float: left;
}
.label-i{
  width: 120rpx;
  height: 100%;
  line-height: 80rpx;
  font-size: 28rpx;
  color: #313131;
  position: absolute;
  left: 0;
  top: 0;
  text-align: center;  
}
.label-i::after{
  content: "";
  width: 1rpx;
  height: 46rpx;
  background: #262121;
  position: absolute;
  right: 0;
  top: 50%;
  margin-top: -23rpx;
 
}
.label image{
  width: 34rpx;
  position: absolute;
  left: 140rpx;
  top: 50%;
  transform: translateY(-50%);
}
.label input{
  width: 410rpx;
  border: 0;
  background: transparent;
  margin: 0;
  padding: 0;
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  font-size: 26rpx;
}
.search-bind{
  width: 100rpx;
  height: 80rpx;
  text-align: center;
  

 
  position: absolute;
  right: 0;
  top: 50%;
  margin-top: -40rpx;
  overflow: hidden;
  box-sizing: border-box;
  z-index: 800;
}
.search-bind button{
  width: 100%;
  height: 100%;
  background: #17b356;
  line-height: 80rpx;
  font-size: 30rpx;
  color: #fff;
  margin: 0;
  padding: 0;
  border: 0;
}
.map-box{
  padding: 110rpx 0 0;
  box-sizing: border-box;
}
.map-box.active{
  padding: 110rpx 0 600rpx;
}


/* 搜索返回地址 */
.list{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 600rpx;
  overflow: hidden;
  overflow-y: scroll;
  background: #fff;
  z-index: 88;
  padding: 20rpx;
}
.list-li{
  width: 100%;
  height: 130rpx;
  position: relative;
  padding-left: 76rpx;
  box-sizing: border-box;
}
.list-img{
  width: 33rpx;
  height: auto;
  position: absolute;
  left: 10rpx;
  top: 50%;
  transform: translateY(-50%);
}
.list-img image{
  width: 100%;
}
.list-r{
  width: 100%;
}
.list-p{
  font-size: 30rpx;
  color: #434343;
  line-height: 50rpx;
}
.list-span{
  font-size: 26rpx;
  color: #707070;
  line-height: 30rpx;
  margin-top: 10rpx;
}
.list.active .list-p{
  color: #17b356;
}
.bindBtn{
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 10rpx;
  font-size: 24rpx;
  color: #fff;
  background: #17b356;
  position: absolute;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 10rpx;
}

/* 关键词 */
.vague{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  z-index: 99;
  padding: 110rpx 0 0 ;
  box-sizing: border-box;
}
.vague view{
  height: 80rpx;
  line-height: 80rpx;
  border-bottom: 1rpx solid #eee;
  padding: 0 40rpx;
  font-size: 30rpx;
  color: #313131;
}

// pages/user/site/search/index.js
var app = getApp();
var mapRequire = require('../../../../qqmap/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    thisCity:'',//当前城市
    range:"",//配送范围
    shapLocation:'',//商铺坐标
    siteData:[],//地址列表
    vague:[],//关键词输入提示
    scale: 16,//缩放级别
    latitude: '',
    longitude: '',
    markers:[{
      iconPath: "/imgs/address.png",
      latitude: 0,
      longitude: 0,
      width: 15,
      height: 18
    }],
    listIndex:"0",//选择地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //获取屏幕信息
    wx.getSystemInfo({
      success: function (res) {
        // 高度,宽度 单位为px
        that.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    });
    //key值
    qqmapsdk = new mapRequire({
      key: '你的key值'
    });
    this.map();

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var shapLocation = '29.52168,106.56256';//商户坐标
    var range = 2000;//配送距离(米)
  
    var thisCity = app.globalData.address ? app.globalData.address: that.data.thisCity;//获取当前城市
   
    if(!thisCity){
      wx.showLoading({
        title: '加载中',
      })
      var setIn = setInterval(function () {
        thisCity = that.data.thisCity;
        if (thisCity) {
          that.setData({
            thisCity: thisCity,
          })
          wx.hideLoading();
          clearInterval(setIn)
        }
        console.log(thisCity)
      }, 100)
      
    }else{
      that.setData({
        thisCity: thisCity,
      })
    }
    
    that.setData({
      shapLocation: shapLocation,
      range: range,
    })
  },
  /**
  * 地图初始化
  */
  map:function(){
    var that = this;
    var latitude="";
    var longitude="";
    var thisCity = '';
    wx.getLocation({
      success: function(res) {
        location = { latitude: res.latitude, longitude: res.longitude }
        qqmapsdk.reverseGeocoder({
          location: location,
          success: function (res) {
            thisCity = res.result.address_component;
            that.setData({
              thisCity: thisCity
            })
          }
        })
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
      },
    });
  },


  /**
   * 关键词输入提示
   */
  getsuggest: function (e) {
    var that = this;
    var value = e.detail.value;
    var keyword = String(value);
    var vague = [];
    that.setData({
      inputVal: value
    })
    qqmapsdk.getSuggestion({
      keyword: keyword,//搜索关键词
      region:that.data.thisCity.city, //设置城市名,限制关键词所示的地域范围,非必填参数
      success: function (res) {
       
        for (var i = 0; i < res.data.length; i++) {
          vague.push({
            title: res.data[i].title,
            data: 
              {
                title: res.data[i].title,//名字
                id: res.data[i].id,//id
                da_info: res.data[i].city,//所属省市区
                address: res.data[i].address ? res.data[i].address:"",//具体地址
                location: res.data[i].location ? res.data[i].location:"",//坐标
                category: res.data[i].category ? res.data[i].category:"",//类型
                tel: res.data[i].tel ? res.data[i].tel:"",//电话
                checked: false,//是否在选中
                scope: false,//是否在范围以内
              }
          })
        };
        that.setData({
          vague: vague,
        })
      }
    })
  },

  /**
   * 关键词确认
   */
  bindSearch: function (e) {
    var that = this;
    var val = e.currentTarget.dataset.name;
    var data = e.currentTarget.dataset.data;
    var vague = [];
    if(!val & !data){
      this.formSubmit();
    }else{
      that.setData({
        inputVal: val,
        vague: vague
      })
      this.search(val, data);
    }
  },
  /**
   * form地址搜索
   */
  formSubmit:function(e){
    var that = this;
    var keyword = e.detail.value.site;
    this.search(keyword);
  },
  /**
   * 
   */
  search: function (e,data){
    var that = this;
    var siteData = [];
    if (e){
      wx.showLoading({
        title: '加载中',
      })
      var keyword = String(e);
      var shapLocation = this.data.shapLocation;//商铺坐标 
      var data = data;
      qqmapsdk.search({
        keyword: keyword,//搜索关键词
        location: shapLocation,//设置周边搜索中心点
        success: function (res) {
          if (res.data.length > 0) {
            for (var i = 0; i < res.data.length; i++) {
              siteData.push({
                title: res.data[i].title,//名字
                id: res.data[i].id,//id
                da_info: res.data[i].da_info,//所属省市区
                address: res.data[i].address,//具体地址
                location: res.data[i].location,//坐标
                category: res.data[i].category,//类型
                tel: res.data[i].tel,//电话
                checked: false,//是否在选中
                scope: false,//是否在范围以内
              })
            };
          } else {
            siteData.push(data)
          }
          var set = setInterval(function () {
            if (siteData.length > 0) {
              wx.hideLoading();
              //重新获取定位。
              wx.getLocation({
                success: function (res) {
                  that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                  })
                },
              });
              that.setData({
                siteData: siteData
              })
              clearInterval(set);
            }
          }, 100)

        },
      })
    }else{
      wx.showToast({
        title: '请输入地址',
        icon: 'none',
        duration: 1000
      })
    }
  
  },


  /**
   * 选择地址
   */
  bindDistance:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index ? e.currentTarget.dataset.index:"0";
    var location = e.currentTarget.dataset.location;
    var siteData = this.data.siteData;
    var shapLocation = this.data.shapLocation;//起点地址坐标
    var range = this.data.range;//配送范围
    wx.showLoading({
      title: '加载中',
    })

    for(var i=0;i<siteData.length;i++){
      if (index == (i + 1)){
        siteData[i].checked = true;
        var toLocation = siteData[i].location.lat + "," + siteData[i].location.lng
        toLocation = String(toLocation);
        var title = siteData[i].title;

        /**
         * 计算距离
         * form=>起点坐标
         * to=>终点坐标
         * scope=>距离
         */
        qqmapsdk.calculateDistance({
          mode: 'driving',//可选值:'driving'(驾车)、'walking'(步行),不填默认:'walking',可不填
          from: shapLocation,
          to: toLocation,
          success: function (res) {
            var distance = res.result.elements[0].distance;/**起点到终点的距离,单位:米,如果radius半径过小或者无法搜索到,则返回-1 */
            var duration = res.result.elements[0].duration;/**表示从起点到终点的结合路况的时间,秒为单位。 注:步行方式不计算耗时,该值始终为0 */
            if (distance <= range){
              wx.showModal({
                title: '提示',
                content: '该地址在配送范围以内,是否选择为收货地址',
                success:function(res){
                  if(res.confirm){
                    wx.navigateTo({
                      url: '/pages/user/site/edit/index?title=' + title
                    })
                  }
                }
              })
            }else{
              wx.showModal({
                title: '提示',
                content: '该地址不在我们的配送范围之内,请重新选择地址',
              })
            }
          }
        })
        
      }else{
        siteData[i].checked = false;
      }
    }
    var set = setInterval(function(){
      if (siteData.length > 0) {
        wx.hideLoading()
        that.setData({
          siteData: siteData
        })
        clearInterval(set);
      }
    },100)
    that.setData({
      listIndex: index
    })
  },
})
//app.js
App({

  globalData: {
    address:null,
  },

})
//app.json
//permission 很重要、只有配置了permission。地图才能使用哦
 "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  }