// pages/map/map.js
const {
  getAddressByLonLat
} = require('../../api/api')
Page({
  data: {
    latitude:31.8512,
    longitude:117.26061,
    scale:13,
    lonLat:[],
    addr:'',
    markers:[{
      ...{
        latitude: 31.8512,
        longitude: 117.26061,
        iconPath: '../../img/canvas-location.png',
        width: '34px',
        height: '34px',
        rotate: 0,
        alpha: 1
      }
    }]
  },
  /** 去导航 **/
  mapFn(){
    wx.openLocation({
      latitude:this.data.latitude,
      longitude:this.data.longitude,
      name:this.data.addr,
      scale: 18,
    });
  },
  onLoad(options) {
    console.log("options",options);
    if(options.q){
      let url = options.q ? decodeURIComponent(options.q) : '';
      console.log("url",url);
      let index1 = url.indexOf("lonLat");
      let lonLat = url.slice(index1 + 7).split(",");
      console.log("lonLat",lonLat);
      if(lonLat.length){
        let lonLatA = Number(lonLat[0]) + ',' + Number(lonLat[1]);
        this.getAddress(lonLatA,res=>{
          this.setData({
            latitude:Number(lonLat[1]),
            longitude:Number(lonLat[0]),
            lonLat:lonLatA,
            addr:res,
            markers:[{
              ...{
                latitude: Number(lonLat[1]),
                longitude: Number(lonLat[0]),
                iconPath: '../../img/canvas-location.png',
                width: '34px',
                height: '34px',
                rotate: 0,
                alpha: 1
              }
            }],
          });
          wx.openLocation({
            latitude:Number(lonLat[1]),
            longitude:Number(lonLat[0]),
            name:res,
            scale: 18,
          });
        });
      }
    }else{
      wx.showToast({
        title: '未获取到地址',
        icon:'none'
      });
    }
  },
  //经纬度获取地址
  getAddress(lonLat,callback){
    getAddressByLonLat({
      lonLat: lonLat
    }).then(res=>{
      if (res.code == 200) {
        this.setData({
          addr:res.data
        });
        callback(res.data);
      } else {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    });
  },
  onReady() {

  },
  onShow() {
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})