收藏
回答

小程序自定义组件中使用map无法通过getCenterLocation获取经纬度

框架类型 问题类型 终端类型 微信版本 基础库版本
小程序 Bug 工具 6.6.3 1.9.0

小程序自定义组件中封装使用map无法通过getCenterLocation获取经纬度,但是在Page 注册页面中直接调用就可以,不知道这个是小程序自定义组件问题不? 1. 在page 页面中调用是可以通过

regionchange回调通过getCenterLocation获取到中心节点经纬度。

 data: {

   

markers: [{

iconPath: "https://huotu.oss-cn-shanghai.aliyuncs.com/wxx/add_cart@3x.png",

id: 0,

latitude: 23.099994,

longitude: 113.324520,

width: 50,

height: 50

}],

polyline: [{

points: [{

longitude: 113.3245211,

latitude: 23.10229

}, {

longitude: 113.324520,

latitude: 23.21229

}],

color: "#FF0000DD",

width: 2,

dottedLine: true

}],

controls: [{

id: 1,

iconPath: 'https://huotu.oss-cn-shanghai.aliyuncs.com/wxx/conplete-center@3x.png',

position: {

left: 0,

top: 300 - 50,

width: 50,

height: 50

},

clickable: true

}]


},

onShow: function () {

    this.mapCtx = wx.createMapContext('myMap')
 },
 regionchange(e) {
   if(e.type == 'end') {
     console.log(e)
     console.log(this.mapCtx)
     this.mapCtx.getCenterLocation({
       success: (res) => {
         console.log(res)
       },
     })
   }
    
 },


2. 但是经同样额代码放在自定义组件就不可以获取到经纬度

组件代码(map-native):

// pages/components/map-native/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
 
  },
 
  /**
   * 组件的初始数据
   */
  data: {
    markers: [{
      iconPath: "https://huotu.oss-cn-shanghai.aliyuncs.com/wxx/add_cart@3x.png",
      id: 0,
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
    polyline: [{
      points: [{
        longitude: 113.3245211,
        latitude: 23.10229
      }, {
        longitude: 113.324520,
        latitude: 23.21229
      }],
      color: "#FF0000DD",
      width: 2,
      dottedLine: true
    }],
    controls: [{
      id: 1,
      iconPath: 'https://huotu.oss-cn-shanghai.aliyuncs.com/wxx/conplete-center@3x.png',
      position: {
        left: 0,
        top: 300 - 50,
        width: 50,
        height: 50
      },
      clickable: true
    }],
    mapCtx: null,
  },
  ready() {
      this.setData({
        mapCtx: wx.createMapContext('myMap')
      })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    regionchange(e) {
      if (e.type == 'end') {
        console.log(e)
        console.log(this.data.mapCtx)
        console.log(this.data.mapCtx.getCenterLocation)
        this.data.mapCtx.getCenterLocation({
          success: (res) => {
            console.log(res)
          },
          fail: (res) => {
            console.log(res)
          },
          complete: (complete) => {
            console.log(2222)
          }
        })
      }
 
    },
  }
})

模板:

<map id="myMap" longitude="113.324520" latitude="23.099994" scale="14" controls="{{controls}}" bindcontroltap="controltap" markers="{{markers}}" bindmarkertap="markertap" polyline="{{polyline}}" bindregionchange="regionchange" show-location style="width: 400px; height: 300px;"></map>


页面调用:

<map-native></map-native>



回答关注问题邀请回答
收藏

2 个回答

登录 后发表内容