寫在前面:我只是一個前端小白,文章中的提到可能會有不足之處,僅提供一個參考。若有不完善的地方,歡迎各位大佬指出!,希望對你有幫助!
好了,入正題。其實(shí)之前也被這問題困擾過,在網(wǎng)上也查了一番,沒找到解決方法。直到今天,在GitHub 冒昧地向大佬提了一個 issue,才點(diǎn)醒了我。其實(shí)是因?yàn)樘^急功近利了,沒有認(rèn)真閱讀 vue-baidu-map 提供參考文檔,也有可能是看過然后忘記了!
首先要明確一點(diǎn)(文檔原話):由于百度地圖 JS API 只有 JSONP 一種加載方式,因此 BaiduMap 組件及其所有子組件的渲染只能是異步的。因此,請使用在組件的 ready 事件來執(zhí)行地圖 API 加載完畢后才能執(zhí)行的代碼,不要試圖在 vue 自身的生命周期中調(diào)用 BMap 類,更不要在這些時機(jī)修改 model 層。
錯誤用法
我試過,以上這種方法好像是可行,效果可以出來,但我們最好采用作者提供的正確方法!
正確用法
推薦這種方法!那下面解決進(jìn)入頁面自動定位的方法也是在這里。
下面是我的寫法,僅供參考,有不足請指出,我只是一個小白,哈哈!
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> <!-- 自定義定位圖標(biāo)覆蓋物 --> <bm-marker :position="autoLocationPoint" :icon="{url: require('../../svg/location.svg'), size: {width: 18, height: 18}}" v-if="initLocation"> </bm-marker> </baidu-map></template>JS實(shí)現(xiàn):
<script> export default { data () { return { // 省略一部分 autoLocationPoint: {lng: 0, lat: 0}, initLocation: false, } }, methods: { handler ({BMap, map}) { let _this = this; // 設(shè)置一個臨時變量指向vue實(shí)例,因?yàn)樵诎俣鹊貓D回調(diào)里使用this,指向的不是vue實(shí)例; var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(r){ console.log(r); _this.center = {lng: r.longitude, lat: r.latitude}; // 設(shè)置center屬性值 _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude}; // 自定義覆蓋物 _this.initLocation = true; console.log('center:', _this.center) // 如果這里直接使用this是不行的 },{enableHighAccuracy: true}) // 下面注釋是百度地圖API官方實(shí)現(xiàn)方法,因?yàn)槲沂褂米远x圖標(biāo)覆蓋物,所以沒有使用這種方法! // 如使用以下這種方法,那么我Template里所寫的自定義定位圖標(biāo)代碼是不需要的 // 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>
新聞熱點(diǎn)
疑難解答
圖片精選