使用高德定位 项目初始化时候加载

281 阅读1分钟

## 在项目入口vue文件中(app.vue)中引入高德插件

<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=高德KEY"></script>

在项目入口vue文件中(app.vue)调用高德初始化方法

将拿到的经纬度存入localStorage中  需要的地方调用即可
init () {
  var map = new AMap.Map('mapContainer', {
    resizeEnable: true
  })
  let that = this
  map.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是具体的定位信息
      // that.lng = data.position.lng
      // that.lat = data.position.lat
      //Lockr.set('position', data)//这是引入的lockr插件,将data数据存入localStorage
    }

    function onError (error) {
      // 定位出错
      console.log(error)
    }
  })
}