vue引入高德地图后,如何获取到详细定位的经纬度

主要是this指向的问题

1.在data里面先定义经纬度

data () {
    return {
      longit:   , // 经度
      latit:   ,  // 纬度
    }
  }

2.在methods里面

  • 1.生成地图并获取当前位置的经纬度

getMap () {
    // 先定义that = this   
  var that = this   

  // 生成地图
  var map = new window.AMap.Map( container , {
    resizeEnable: true,
    zoom: 11,
    showIndoorMap: false, // 是否在有矢量底图的时候自动展示室内地图,PC默认true,移动端默认false
    dragEnable: true, // 地图是否可通过鼠标拖拽平移,默认为true
    keyboardEnable: false, // 地图是否可通过键盘控制,默认为true
    doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图,默认为true
    zoomEnable: true, // 地图是否可缩放,默认值为true
    rotateEnable: false, // 地图是否可旋转,3D视图默认为true,2D视图默认false
    viewMode:  3D 
  })


  // 获取到当前位置的定位
  AMap.plugin( AMap.Geolocation , function() {
    var geolocation = new AMap.Geolocation({
    // 是否使用高精度定位,默认:true
    enableHighAccuracy: true,
    // 设置定位超时时间,默认:无穷大
    timeout: 10000,
    // 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
    buttonOffset: new AMap.Pixel(10, 20),
    //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
    zoomToAccuracy: true,     
    //  定位按钮的排放位置,  RB表明右下
    buttonPosition:  RB 
    })

    geolocation.getCurrentPosition()
    AMap.event.addListener(geolocation,  complete , onComplete)
    AMap.event.addListener(geolocation,  error , onError)

   
    function onComplete (data) {
      // data是具体的定位信息
      console.log( data是具体的定位信息 , data)

      // 这里使用that而不是this,如果使用this,则无法在其他地方获取到这里的经纬度
      that.longit = data.position.lng
      that.latit = data.position.lat
    }
     function onError (data) {
       // 定位出错
       console.log( 定位失败 )
     }
  })
  that.maps = map
}

  • 2.拿到步骤1获取到的经纬度(methods里面),此处使用this而不是that,之前是由于在getMap ()方法里面定义了that = this,这里未定义,可以直接用this

 conf () {
  console.log( 确定 )
  console.log( 666 , this.longit, this.latit)
},

ps:conf ( )在一直拿不到getMap ( )里的经纬度,后来发现是getMap ( )里的this和AMap里的this指向不同,利用var that = this解决了这个问题

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
泰蕾莎泰斯塔羅莎的头像 - 鹿快
评论 抢沙发

请登录后发表评论

    暂无评论内容