首页 > 语言 > JavaScript > 正文

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

2024-05-06 15:34:47
字体:
来源:转载
供稿:网友

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

好了,入正题。其实之前也被这问题困扰过,在网上也查了一番,没找到解决方法。直到今天,在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>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选