当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue-baidu-map 进入页面自动定位的解决方案(推荐)

vue-baidu-map 进入页面自动定位的解决方案(推荐)

2018年05月11日  | 移动技术网IT编程  | 我要评论

中融信托圭顿财富,做鸭的经历,爱的被告电视剧中文版

写在前面:我只是一个前端小白,文章中的提到可能会有不足之处,仅提供一个参考。若有不完善的地方,欢迎各位大佬指出!,希望对你有帮助!

好了,入正题。其实之前也被这问题困扰过,在网上也查了一番,没找到解决方法。直到今天,在github 冒昧地向大佬提了一个 issue,才点醒了我。其实是因为太过急功近利了,没有认真阅读 vue-baidu-map 提供,也有可能是看过然后忘记了!

首先要明确一点():由于百度地图 js api 只有 jsonp 一种加载方式,因此 baidumap 组件及其所有子组件的渲染只能是异步的。因此,请使用在组件的 ready 事件来执行地图 api 加载完毕后才能执行的代码,不要试图在 vue 自身的生命周期中调用 bmap 类,更不要在这些时机修改 model 层。

错误用法

 我试过,以上这种方法好像是可行,效果可以出来,但我们最好采用作者提供的正确方法!

正确用法

 推荐这种方法!那下面解决进入页面自动定位的方法也是在这里。

 下面是我的写法,仅供参考,有不足请指出,我只是一个小白,哈哈!

template:

<template>
  <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler" @load="loadding" :scroll-wheel-zoom="true"
    :mapstyle="{stylejson: stylejson}">
    <bm-geolocation anchor="bmap_anchor_bottom_right" :showaddressbar="false" :autolocation="true"
      :locationicon="{url: require('../../svg/location.svg'), size: {width: 18, height: 18}}" 
      @locationsuccess="getloctionsuccess" @locationerror="getlocationerror">
    </bm-geolocation>
    <!-- 自定义定位图标覆盖物 -->
    <bm-marker :position="autolocationpoint"
      :icon="{url: require('../../svg/location.svg'), size: {width: 18, height: 18}}" v-if="initlocation">
    </bm-marker>
  </baidu-map>
</template>

js实现:

<script>
  export default {
    data () {
      return {
        // 省略一部分
        autolocationpoint: {lng: 0, lat: 0},
        initlocation: false,
      }
    },
    methods: {
      handler ({bmap, map}) {
        let _this = this;  // 设置一个临时变量指向vue实例,因为在百度地图回调里使用this,指向的不是vue实例;
        var geolocation = new bmap.geolocation();
        geolocation.getcurrentposition(function(r){
          console.log(r);
          _this.center = {lng: r.longitude, lat: r.latitude};   // 设置center属性值
          _this.autolocationpoint = {lng: r.longitude, lat: r.latitude};   // 自定义覆盖物
          _this.initlocation = true; 
          console.log('center:', _this.center)  // 如果这里直接使用this是不行的
        },{enablehighaccuracy: true})

        // 下面注释是百度地图api官方实现方法,因为我使用自定义图标覆盖物,所以没有使用这种方法!
        // 如使用以下这种方法,那么我template里所写的自定义定位图标代码是不需要的
        // var geolocation = new bmap.geolocation();
        // geolocation.getcurrentposition(function(r){
        // if(this.getstatus() == bmap_status_success){
        //   var mk = new bmap.marker(r.point);
        //   map.addoverlay(mk);
        //   map.panto(r.point);
        //   alert('您的位置:'+r.point.lng+','+r.point.lat);
        // }
        // else {
        //   alert('failed'+this.getstatus());
        // }
        // },{enablehighaccuracy: true})
      }
    }
  }
</script>

如果是直接复制代码的朋友请注意,要有选择的复制,因为我没有把全部代码贴出了,直接复制到你的项目是会出问题的!不过这代码比较简单,稍微就能看懂,哈哈!

以上所述是小编给大家介绍的vue-baidu-map 进入页面自动定位的解决方案,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网