陈程的技术博客

  • 关于作者
全栈软件工程师
一个专注于技术研究创新的程序员
  1. 首页
  2. 小程序
  3. 正文

小程序篇-地图助手,异步请求处理等

2020年2月25日 610点热度 0人点赞 0条评论

样式采用colorUI

1.配置:

申请https://lbs.qq.com/ 地图key,

引用官方SDK

qqmap-wx-jssdk.js
2.登录微信公众平台小程序,配置request 合法域名:如图

3.用到的地图API功能点:

地址解析、逆地址解析、距离计算

4.跳转第三方地图,根据手机上已经安装的地图

后台源码:

var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({
  data: {
    MyLocationName:"",
    Mylatitude: null,
    Mylongitude: null,
    Mymarkers:[],
    ActiveList:[
      {
        index:1,
        name:"天隆寺[地铁站]",
        latitude: null, 
        longitude: null,
        color:"grey",
        len:""
      }, {
        index: 2,
        name: "南京市江宁区人民法院",
        latitude: null, 
        longitude: null,
        color: "grey",
        len: ""
      }, {
        index: 3,
        name: "江苏省南京市秦淮区贡院街",
        latitude: null,
        longitude: null,
        color: "grey",
        len: ""
      }
    ]
  },
  SetShadow(e) {
    this.setData({
      shadow: e.detail.value
    })
  },
  select: function(e){
    var index = e.currentTarget.dataset.index;
    //console.log("index:" + e.currentTarget.dataset.index);
    if (index==-1){
      this.OpenMap(-1);
    }else {
      var data = this.data.ActiveList;
      for(var i=0;i<data.length;i++){
        if(data[i].index==index)
        {
          var locat = data[i];
          console.log(locat);
          this.OpenMap(locat);
        }
      }
    }
  },
  OpenMap: function (locat) {
    console.log("e:" + locat);
    var _this = this;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        console.log(res);
        var keyword= _this.data.MyLocationName;
        var latitude = res.latitude;
        var longitude = res.longitude;
        if (locat != -1) {
          keyword = locat.name;
          latitude = locat.latitude;
          longitude = locat.longitude;
        }
        wx.openLocation({
          latitude,
          longitude,
          address: keyword,
          scale: 18
        })
      }
    })
  },
  onReady: function () {
   
  },
  onLoad: function () {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'SN7BZ-2PK6W-RYSR5-RRWUU-CSHYE-4KBYA'
    });
  
    var _this=this;
    this.GetLocationName();
    var PromiseAllArr=[];
    for (var i = 0; i < this.data.ActiveList.length; i++) {
      PromiseAllArr.push(this.GetLocation(this.data.ActiveList[i], i));
    }
    
    Promise.all(PromiseAllArr).then(function () {
      console.log(_this.data.ActiveList);
      _this.GetDistance(_this.data.ActiveList);
    }).catch(reason => {
      console.log(reason)
    });
  },
  //计算距离
  GetDistance(locat) {
        var _this = this;
        //调用距离计算接口
        qqmapsdk.calculateDistance({
              //mode: 'driving',//可选值:'driving'(驾车)、'walking'(步行),不填默认:'walking',可不填
              //from参数不填默认当前地址
              //获取表单提交的经纬度并设置from和to参数(示例为string格式)
              from:'', //若起点有数据则采用起点坐标,若为空默认当前地址
              to: locat, //终点坐标
              success: function (res) {//成功后的回调
                  console.log(res);
                  var res = res.result;
                for (var i = 0; i < res.elements.length; i++) {
                  for(var j=0; j < locat.length;j++){
                    if (locat[j].latitude == res.elements[i].to.lat &&
                      locat[j].longitude == res.elements[i].to.lng){
                      var item = 'ActiveList[' + j + '].len';
                      _this.setData({ //设置并更新distance数据
                         [item]: res.elements[i].distance
                      });
                    }
                  }
                }
                //排序
                var data = _this.data.ActiveList;
                var newdata = data.sort(_this.compare('len'));
                _this.setData({
                  ActiveList: newdata
                });
                console.log("newdata" + newdata);
              },
              fail: function (error) {
                  console.error(error);
              },
              complete: function (res) {
                 // console.log(res);
              }
        });
  },
  //比较大小 排序
  compare(key){
    return function (value1, value2) {
      var val1 = value1[key];
      var val2 = value2[key];
      return val1 - val2;
    }
  },
  //获取指定位置坐标
  GetLocation: function (myLocat, index){
    var _this = this;
    return new Promise(function (resolve, reject) {
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: myLocat.name, //地址参数,例:固定地址,address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        //根据地址解析在地图上标记解析地址位置
        var mark={
           id:myLocat.index,
           title: myLocat.name,
           latitude: latitude,
           longitude: longitude,
           iconPath:"../../resource/map.png",
           callout: {
              content: myLocat.name,
              padding: 10,
              display: 'ALWAYS',
              textAlign: 'center'
              }
            };
        var count = _this.data.Mymarkers.length;
        var item = 'Mymarkers[' + count + ']';
        var lat = 'ActiveList[' + index + '].latitude';
        var lon = 'ActiveList[' + index + '].longitude';
        _this.setData({ 
          [item]: mark,
          [lat]: latitude,
          [lon]: longitude
        });
        //console.log(_this.data.ActiveList);
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
        return resolve("true");
      }
    });
    })
  },
  //获取当前位置,逆名称解析
  GetLocationName: function() {
    var _this = this;
    qqmapsdk.reverseGeocoder({
      location: '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      //get_poi: 1, //是否返回周边POI列表:1.返回;0不返回(默认),非必须参数
      success: function (res) {//成功后的回调
        console.log(res);
        var res = res.result;
        _this.setData({ //设置并更新distance数据
          MyLocationName:res.address,
          Mylatitude: res.location.lat,
          Mylongitude: res.location.lng,
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
       // console.log(res);
      }
    })
  }
})

小程序wxml样式源码:

<map latitude="{{Mylatitude}}" longitude ="{{Mylongitude}}" markers="{{Mymarkers}}" show-location include-points="{{Mymarkers}}" style="width:100%;height:200px"> 
</map>

 

标签: js 地图 微信小程序
最后更新:2021年4月2日

博主

全栈工程师,侧重项目技术解决方案规划和开发

打赏 点赞
下一篇 >

文章评论

取消回复

分类
  • .NET (65)
  • docker (3)
  • linux (12)
  • python (20)
  • web (14)
  • 小程序 (4)
  • 数据库 (2)
  • 未分类 (4)
  • 杂七杂八 (10)
标签聚合
python winform js C# DevExpress centos nginx linux
最新 热点 随机
最新 热点 随机
.NET开发手册标准参考 招募兼职前端开发 Centos安装dotnet6环境 VS上切换分支,vs编译运行出现bug,A fatal error was encountered彻底解决方案 用C#封装一个线程安全的缓存器,达到目标定时定量更新入库 C#通过特性的方式去校验指定数据是否为空
通过tablesorter.js ,table表格快速实现自动排序 DevExpress控件-GridControl控件中添加一列复选框并进行相关操作 tableLayoutPanel刷新控件值导致控件闪烁的解决方案 关于使用webBrowser操作HTML的帮助类 WTM部署CentOS验证码错误 django学习笔记

COPYRIGHT © 2021 陈程的技术博客. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS